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.utils.workflow import WorkflowStep


class LoadSourceContentStep(WorkflowStep[DocUpdateFromFeatureV2Context]):
    step_id = "step2_load_source_content"
    title = "Загрузка системной аналитики"

    async def run(self, context: DocUpdateFromFeatureV2Context) -> DocUpdateFromFeatureV2Context:
        if context.answer:
            return context
        if not context.source_ref:
            return context
        if context.source_kind == "confluence_url":
            context.issues.append("Confluence source пока не реализован (stub).")
            return context
        if context.source_kind != "markdown_file":
            context.issues.append("Поддерживается только markdown-файл (.md).")
            return context

        source_path = Path(context.source_ref)
        if not source_path.exists() or not source_path.is_file():
            context.issues.append(f"Файл системной аналитики не найден: {context.source_ref}")
            return context
        try:
            context.source_content = source_path.read_text(encoding="utf-8")
            context.project_root = self._resolve_project_root(source_path).as_posix()
        except Exception as exc:
            context.issues.append(f"Не удалось прочитать системную аналитику: {exc}")
        return context

    def _resolve_project_root(self, source_path: Path) -> Path:
        parts = list(source_path.parts)
        if "_incoming" in parts:
            idx = parts.index("_incoming")
            if idx > 0:
                return Path(*parts[:idx])
        return source_path.parent

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

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