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.schemas.chat import TaskResultType


class FallbackWorkflow:
    workflow_id = "fallback"

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

    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},
            )
        emit_status_block(
            ctx,
            block_id="rag_retrieval",
            title="RAG Retrieval",
            lines=["not used in fallback workflow"],
        )
        if self._llm is None:
            answer = "Пока не удалось подобрать специализированный workflow для этого запроса."
        else:
            payload = json.dumps(
                {
                    "question": ctx.message,
                    "attachments": list(ctx.attachments),
                    "confluence_urls": list(ctx.enriched_context.get("confluence_urls") or []),
                },
                ensure_ascii=False,
                indent=2,
            )
            answer = self._llm.generate(
                "fallback_answer",
                payload,
                log_context="agent.workflow.fallback",
                trace=ctx.trace.module("llm") if ctx.trace is not None else None,
            ).strip()
        emit_status_block(
            ctx,
            block_id="workflow",
            title="Task Workflow",
            lines=[f"workflow_id: {self.workflow_id}"],
        )
        emit_status_block(
            ctx,
            block_id="evidence_gate",
            title="Evidence Gate",
            lines=["not applied in fallback workflow"],
        )
        result = WorkflowExecutionResult(
            result_type=TaskResultType.ANSWER,
            answer=answer,
            meta={"workflow_id": self.workflow_id, "intent": getattr(ctx.route_result, "intent", "")},
        )
        if ctx.trace is not None:
            ctx.trace.module("task_workflow").log(
                "completed",
                {"workflow_id": self.workflow_id, "answer_length": len(answer)},
            )
        return result
