from __future__ import annotations

from typing import TYPE_CHECKING
from typing import Any

from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.steps.step4_prepare_tasks.services import (
    DocsCatalogLoader,
    RequirementTaskBuilder,
    RequirementTaskOrderer,
)
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

if TYPE_CHECKING:
    from app.core.rag.persistence.query_repository import RagQueryRepository


class PrepareRequirementTasksStep(WorkflowStep[DocUpdateFromFeatureV2Context]):
    step_id = "step4_prepare_tasks"
    title = "Подготовка задач по страницам документации"

    def __init__(self, llm: AgentLlmService, query_repository: "RagQueryRepository | None" = None) -> None:
        self._catalog_loader = DocsCatalogLoader(query_repository=query_repository)
        self._task_builder = RequirementTaskBuilder(llm)
        self._task_orderer = RequirementTaskOrderer()

    async def run(self, context: DocUpdateFromFeatureV2Context) -> DocUpdateFromFeatureV2Context:
        if context.answer or not context.requirements:
            return context
        self._catalog_loader.load(context)
        context.requirement_tasks = self._task_orderer.order(self._task_builder.build(context))
        if not context.requirement_tasks:
            context.issues.append("Не удалось подготовить задачи по разделу 6 аналитики.")
        return context

    def trace_input(self, context: DocUpdateFromFeatureV2Context) -> dict[str, Any]:
        return {
            "requirements_count": len(context.requirements),
            "requirements": [
                {"section_key": item.section_key, "heading": item.heading, "metadata": dict(item.metadata)}
                for item in context.requirements
            ],
        }

    def trace_output(self, context: DocUpdateFromFeatureV2Context) -> dict[str, Any]:
        return {
            "docs_catalog_rows_count": len(context.docs_catalog_rows),
            "tasks": [
                {
                    "section_key": item.section_key,
                    "heading": item.heading,
                    "doc_id": item.doc_id,
                    "doc_type": item.doc_type,
                    "application": item.application,
                    "platform": item.platform,
                    "domain": item.domain,
                    "sub_domain": item.subdomain,
                    "action": item.action.value,
                    "path": item.path,
                }
                for item in context.requirement_tasks
            ],
        }
