from __future__ import annotations

import json

from app.modules.agent.llm import AgentLlmService
from app.modules.agent.task_runtime.models import TaskRuntimeContext, WorkflowExecutionResult
from app.modules.agent.task_runtime.status_events import emit_status_block
from app.modules.agent.task_runtime.templates import DocumentationTemplateRegistry
from app.schemas.chat import TaskArtifact, TaskResultType


class DocumentationGenerationWorkflow:
    workflow_id = "docs_generation"

    def __init__(
        self,
        llm: AgentLlmService | None,
        templates: DocumentationTemplateRegistry | None = None,
    ) -> None:
        self._llm = llm
        self._templates = templates or DocumentationTemplateRegistry()

    def run(self, ctx: TaskRuntimeContext) -> WorkflowExecutionResult:
        template = self._templates.default()
        emit_status_block(
            ctx,
            block_id="rag_retrieval",
            title="RAG Retrieval",
            lines=["not used in docs_generation workflow"],
        )
        answer = self._generate(ctx, template)
        emit_status_block(
            ctx,
            block_id="workflow",
            title="Task Workflow",
            lines=[
                f"workflow_id: {self.workflow_id}",
                f"template_id: {template.template_id}",
            ],
        )
        emit_status_block(
            ctx,
            block_id="evidence_gate",
            title="Evidence Gate",
            lines=["not applied in docs_generation workflow"],
        )
        artifact = TaskArtifact(
            artifact_type=TaskResultType.DOCUMENTATION,
            title=template.title,
            content=answer,
            format="markdown",
            template_id=template.template_id,
            source_refs=list(ctx.enriched_context.get("confluence_urls") or []),
        )
        return WorkflowExecutionResult(
            result_type=TaskResultType.DOCUMENTATION,
            answer=answer,
            artifacts=[artifact],
            meta={"workflow_id": self.workflow_id, "intent": getattr(ctx.route_result, "intent", "")},
        )

    def _generate(self, ctx: TaskRuntimeContext, template) -> str:
        if self._llm is None:
            return self._fallback(template)
        payload = json.dumps(
            {
                "question": ctx.message,
                "template_id": template.template_id,
                "title": template.title,
                "sections": list(template.sections),
                "attachments": list(ctx.attachments),
                "files": list(ctx.files),
                "context": dict(ctx.enriched_context),
            },
            ensure_ascii=False,
            indent=2,
        )
        return self._llm.generate("docs_template_generation", payload, log_context="agent.workflow.docs_generation").strip()

    def _fallback(self, template) -> str:
        sections = "\n".join(f"## {name}\n\nTBD" for name in template.sections)
        return f"# {template.title}\n\n{sections}\n"
