from __future__ import annotations

from typing import Any

from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.steps.step5_execute_subprocesses.services import (
    TaskChangeExecutor,
)
from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.workflow_runtime.context import (
    DocUpdateFromFeatureV2Context,
)
from app.core.agent.utils.llm import AgentLlmService
from app.core.agent.utils.workflow import WorkflowStep


class ExecuteRequirementSubprocessesStep(WorkflowStep[DocUpdateFromFeatureV2Context]):
    step_id = "step6_execute_subprocesses"
    title = "Выполнение подпроцессов create/edit/delete"

    def __init__(self, llm: AgentLlmService) -> None:
        self._change_executor = TaskChangeExecutor(llm)

    async def run(self, context: DocUpdateFromFeatureV2Context) -> DocUpdateFromFeatureV2Context:
        if context.answer or not context.requirement_tasks:
            return context
        for task in context.requirement_tasks:
            self._change_executor.execute(context, task)
        return context

    def trace_input(self, context: DocUpdateFromFeatureV2Context) -> dict[str, Any]:
        return {
            "tasks": [
                {
                    "section_key": item.section_key,
                    "heading": item.heading,
                    "action": item.action.value,
                    "path": item.path,
                    "doc_type": item.doc_type,
                }
                for item in context.requirement_tasks
            ],
            "rules_count": len(context.rules),
        }

    def trace_output(self, context: DocUpdateFromFeatureV2Context) -> dict[str, Any]:
        return {
            "changeset": [
                {"op": item.op.value, "path": item.path, "reason": item.reason}
                for item in context.changeset
            ],
            "accumulated_pages": [
                {
                    "path": item.path,
                    "doc_id": item.doc_id,
                    "doc_type": item.doc_type,
                    "action": item.action.value,
                }
                for item in context.accumulated_pages
            ],
        }
