from __future__ import annotations

from app.modules.agent.engine.orchestrator.actions.common import ActionSupport
from app.modules.agent.engine.orchestrator.execution_context import ExecutionContext
from app.modules.agent.engine.orchestrator.models import ArtifactType


class DocsActions(ActionSupport):
    def extract_change_intents(self, ctx: ExecutionContext) -> list[str]:
        text = str(self.get(ctx, "source_doc_text", "") or ctx.task.user_message)
        intents = {
            "summary": text[:240],
            "api": ["Update endpoint behavior contract"],
            "logic": ["Adjust reusable business rules"],
            "db": ["Reflect schema/table notes if needed"],
            "ui": ["Adjust form behavior and validation"],
        }
        return [self.put(ctx, "change_intents", ArtifactType.STRUCTURED_JSON, intents)]

    def map_to_doc_tree(self, ctx: ExecutionContext) -> list[str]:
        targets = [
            "docs/api/increment.md",
            "docs/logic/increment.md",
            "docs/db/increment.md",
            "docs/ui/increment.md",
        ]
        return [self.put(ctx, "doc_targets", ArtifactType.STRUCTURED_JSON, {"targets": targets})]

    def load_current_docs_context(self, ctx: ExecutionContext) -> list[str]:
        files_map = dict(ctx.task.metadata.get("files_map", {}) or {})
        targets = (self.get(ctx, "doc_targets", {}) or {}).get("targets", [])
        current = []
        for path in targets:
            current.append(
                {
                    "path": path,
                    "content": str((files_map.get(path) or {}).get("content", "")),
                    "content_hash": str((files_map.get(path) or {}).get("content_hash", "")),
                }
            )
        return [self.put(ctx, "current_docs_context", ArtifactType.STRUCTURED_JSON, {"files": current})]

    def generate_doc_updates(self, ctx: ExecutionContext) -> list[str]:
        intents = self.get(ctx, "change_intents", {}) or {}
        targets = (self.get(ctx, "doc_targets", {}) or {}).get("targets", [])
        bundle = []
        for path in targets:
            bundle.append(
                {
                    "path": path,
                    "content": "\n".join(
                        [
                            f"# Increment Update: {path}",
                            "",
                            "## Scope",
                            str(intents.get("summary", "")),
                            "",
                            "## Changes",
                            "- Updated according to analytics increment.",
                        ]
                    ),
                    "reason": "align docs with analytics increment",
                }
            )
        return [self.put(ctx, "generated_doc_bundle", ArtifactType.DOC_BUNDLE, bundle)]

    def cross_file_validation(self, ctx: ExecutionContext) -> list[str]:
        bundle = self.get(ctx, "generated_doc_bundle", []) or []
        paths = [str(item.get("path", "")) for item in bundle if isinstance(item, dict)]
        has_required = any(path.startswith("docs/api/") for path in paths) and any(path.startswith("docs/logic/") for path in paths)
        report = {"paths": paths, "required_core_paths_present": has_required}
        return [self.put(ctx, "consistency_report", ArtifactType.STRUCTURED_JSON, report)]

    def build_changeset(self, ctx: ExecutionContext) -> list[str]:
        bundle = self.get(ctx, "generated_doc_bundle", []) or []
        changeset = []
        for item in bundle:
            if not isinstance(item, dict):
                continue
            changeset.append(
                {
                    "op": "update",
                    "path": str(item.get("path", "")).strip(),
                    "base_hash": "orchestrator-generated",
                    "proposed_content": str(item.get("content", "")),
                    "reason": str(item.get("reason", "documentation update")),
                    "hunks": [],
                }
            )
        return [self.put(ctx, "final_changeset", ArtifactType.CHANGESET, changeset)]

    def compose_summary(self, ctx: ExecutionContext) -> list[str]:
        count = len(self.get(ctx, "final_changeset", []) or [])
        text = f"Prepared documentation changeset with {count} files updated."
        return [self.put(ctx, "final_answer", ArtifactType.TEXT, text)]
