from __future__ import annotations

from pathlib import Path
from typing import Any

from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.workflow_runtime.context import (
    DocUpdateFromFeatureV2Context,
)
from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.workflow_runtime.models import RuleDocument
from app.core.agent.utils.workflow import WorkflowStep


class LoadRulesStep(WorkflowStep[DocUpdateFromFeatureV2Context]):
    step_id = "step5_load_rules"
    title = "Загрузка правил документации v3"

    def __init__(self, rules_root: Path | None = None) -> None:
        self._rules_root = rules_root or self._discover_rules_root()

    async def run(self, context: DocUpdateFromFeatureV2Context) -> DocUpdateFromFeatureV2Context:
        if context.answer:
            return context
        if not self._rules_root.exists():
            context.issues.append(f"Папка rules не найдена: {self._rules_root.as_posix()}")
            return context
        loaded: list[RuleDocument] = []
        for item in sorted(self._rules_root.rglob("*.md")):
            try:
                loaded.append(
                    RuleDocument(
                        name=item.relative_to(self._rules_root).as_posix(),
                        content=item.read_text(encoding="utf-8"),
                    )
                )
            except Exception as exc:
                context.issues.append(f"Не удалось прочитать rule {item.name}: {exc}")
        context.rules = loaded
        if not context.rules:
            context.issues.append("Rules v2 пустые: не найдено ни одного *.md файла.")
        return context

    def _discover_rules_root(self) -> Path:
        current = Path(__file__).resolve()
        for parent in current.parents:
            candidate = parent / "_process" / "doc_rules_v3"
            if candidate.exists():
                return candidate
        return current.parents[9] / "_process" / "doc_rules_v3"

    def trace_input(self, context: DocUpdateFromFeatureV2Context) -> dict[str, Any]:
        return {"rules_root": self._rules_root.as_posix()}

    def trace_output(self, context: DocUpdateFromFeatureV2Context) -> dict[str, Any]:
        return {
            "rules_count": len(context.rules),
            "rule_names": [item.name for item in context.rules],
        }
