from __future__ import annotations

from typing import Any

from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.steps.step3_parse_requirements.parser import (
    FunctionalRequirementsParser,
)
from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.workflow_runtime.context import (
    DocUpdateFromFeatureV2Context,
)
from app.core.agent.utils.workflow import WorkflowStep


class ParseRequirementsStep(WorkflowStep[DocUpdateFromFeatureV2Context]):
    step_id = "step3_parse_requirements"
    title = "Парсинг раздела функциональных требований"

    def __init__(self, parser: FunctionalRequirementsParser | None = None) -> None:
        self._parser = parser or FunctionalRequirementsParser()

    async def run(self, context: DocUpdateFromFeatureV2Context) -> DocUpdateFromFeatureV2Context:
        if context.answer or not context.source_content:
            return context
        meta, units = self._parser.parse(context.source_content)
        context.analytics_meta = meta
        context.requirements = units

        if not units:
            context.issues.append(
                "Не найден раздел 6 с подразделами 6.x для генерации страниц документации."
            )
        if not context.analytics_meta.analysis_id:
            context.issues.append("Не найден metadata-тег analysis_id в начале аналитики.")
        return context

    def trace_input(self, context: DocUpdateFromFeatureV2Context) -> dict[str, Any]:
        return {"source_content_len": len(context.source_content or "")}

    def trace_output(self, context: DocUpdateFromFeatureV2Context) -> dict[str, Any]:
        return {
            "analytics_meta": {
                "analysis_id": context.analytics_meta.analysis_id,
                "application": context.analytics_meta.application,
                "platform": context.analytics_meta.platform,
                "domain": context.analytics_meta.domain,
                "sub_domain": context.analytics_meta.subdomain,
            },
            "requirements": [
                {
                    "section_key": item.section_key,
                    "heading": item.heading,
                    "metadata": dict(item.metadata),
                }
                for item in context.requirements
            ],
        }
