from __future__ import annotations

from app.core.agent.processes.v2.workflows.doc_update_from_feature.doc_rules_pipeline.loader import DocRulesLoader
from app.core.agent.processes.v2.workflows.doc_update_from_feature.workflow_runtime.context import DocUpdateFromFeatureContext
from app.core.agent.utils.workflow import WorkflowStep


class LoadDocRulesStep(WorkflowStep[DocUpdateFromFeatureContext]):
    step_id = "load_doc_rules"
    title = "Загрузка doc_rules"

    def __init__(self, loader: DocRulesLoader | None = None) -> None:
        self._loader = loader or DocRulesLoader()

    async def run(self, context: DocUpdateFromFeatureContext) -> DocUpdateFromFeatureContext:
        if context.answer or not context.doc_rules_enabled:
            return context
        bundle = self._loader.load()
        context.doc_rules_bundle = bundle
        if not bundle.supported_doc_types:
            context.issues.append(
                f"doc_rules не загружены: отсутствуют пары artifact/template в {self._loader.root.as_posix()}."
            )
        return context

    def trace_output(self, context: DocUpdateFromFeatureContext) -> dict[str, object]:
        supported = sorted((context.doc_rules_bundle.supported_doc_types if context.doc_rules_bundle else set()))
        return {
            "enabled": context.doc_rules_enabled,
            "loaded": context.doc_rules_bundle is not None,
            "supported_doc_types": supported,
            "issues": len(context.issues),
        }
