from __future__ import annotations

from app.modules.agent.runtime.docs_qa_pipeline import DocsQAPipelineRunner
from app.modules.agent.task_runtime.models import TaskRuntimeContext, WorkflowExecutionResult
from app.modules.agent.task_runtime.status_events import emit_status_block
from app.schemas.chat import TaskArtifact, TaskResultType
from app.modules.agent.task_runtime.workflows.docs_qa import _gate_lines, _retrieval_lines


class OpenApiWorkflow:
    workflow_id = "openapi_generation"

    def __init__(self, runner: DocsQAPipelineRunner) -> None:
        self._runner = runner

    def run(self, ctx: TaskRuntimeContext) -> WorkflowExecutionResult:
        if ctx.trace is not None:
            ctx.trace.module("task_workflow").log(
                "started",
                {"workflow_id": self.workflow_id, "message": ctx.message},
            )
        result = self._runner.run(
            ctx.message,
            ctx.rag_session_id,
            conversation_state=ctx.conversation_state,
            mode="full",
            trace=ctx.trace,
        )
        diagnostics = result.diagnostics.model_dump(mode="json")
        emit_status_block(
            ctx,
            block_id="rag_retrieval",
            title="RAG Retrieval",
            lines=_retrieval_lines(diagnostics),
        )
        emit_status_block(
            ctx,
            block_id="workflow",
            title="Task Workflow",
            lines=[
                f"workflow_id: {self.workflow_id}",
                f"prompt: {result.prompt_name}",
                f"answer_mode: {result.answer_mode}",
            ],
        )
        emit_status_block(
            ctx,
            block_id="evidence_gate",
            title="Evidence Gate",
            lines=_gate_lines(diagnostics),
        )
        content = (result.openapi_result.raw_yaml if result.openapi_result else "") or result.answer
        artifact = TaskArtifact(
            artifact_type=TaskResultType.OPENAPI,
            title="OpenAPI Specification",
            content=content,
            format="yaml",
            source_refs=list(result.diagnostics.doc_paths),
        )
        result_payload = WorkflowExecutionResult(
            result_type=TaskResultType.OPENAPI,
            answer=content,
            artifacts=[artifact],
            meta={
                "workflow_id": self.workflow_id,
                "intent": result.router_result.intent,
                "diagnostics": diagnostics,
                "llm_request": result.llm_request,
            },
        )
        if ctx.trace is not None:
            ctx.trace.module("task_workflow").log(
                "completed",
                {"workflow_id": self.workflow_id, "answer_length": len(content or "")},
            )
        return result_payload
