from __future__ import annotations

import asyncio
import json

from app.core.agent.processes.v2.workflows.doc_explain_summary.workflow_runtime.context import DocExplainSummaryContext
from app.core.agent.utils.llm import AgentLlmService
from app.core.agent.utils.process_v2.anchor_signals import route_anchor_summary
from app.core.agent.utils.workflow import WorkflowStep


class GenerateSummaryAnswerStep(WorkflowStep[DocExplainSummaryContext]):
    step_id = "generate_summary_answer"
    title = "Сборка ответа по summary"

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

    async def run(self, context: DocExplainSummaryContext) -> DocExplainSummaryContext:
        if context.answer:
            return context
        if context.gate_decision is not None and not context.gate_decision.passed:
            context.answer = context.gate_decision.message
            context.answer_generated_payload = {
                "answer_mode": context.gate_decision.answer_mode,
                "answer_length": len(context.answer),
            }
            return context
        if not context.workflow_llm_enabled:
            context.answer = self._build_deterministic_answer(context)
            context.answer_generated_payload = {"answer_mode": "grounded_summary", "answer_length": len(context.answer)}
            return context
        if not context.documents:
            context.answer = "Не нашёл подходящих SUMMARY-блоков в документации по этому запросу."
            context.answer_generated_payload = {"answer_mode": "insufficient_evidence", "answer_length": len(context.answer)}
            return context
        context.prompt_input = self._build_prompt_input(context)
        request_id = context.runtime.request.request_id
        context.answer = await asyncio.to_thread(
            self._llm.generate,
            context.prompt_name,
            context.prompt_input,
            log_context=f"agent:{request_id}",
            trace=context.runtime.trace.module("workflow.v2.summary.llm"),
        )
        context.answer_generated_payload = {"answer_mode": "grounded_summary", "answer_length": len(context.answer)}
        return context

    def _build_prompt_input(self, context: DocExplainSummaryContext) -> str:
        blocks = [
            f"Запрос пользователя:\n{context.route.user_query}",
            "Сигналы запроса:\n" + json.dumps(route_anchor_summary(context.route), ensure_ascii=False, indent=2),
            "Найденные SUMMARY-блоки:",
        ]
        for index, item in enumerate(context.documents, start=1):
            blocks.append(
                f"{index}. path: {item.path}\n"
                f"title: {item.title}\n"
                f"match_reason: {item.match_reason}\n"
                f"summary: {item.summary}"
            )
        return "\n\n".join(blocks)

    def _build_deterministic_answer(self, context: DocExplainSummaryContext) -> str:
        if not context.documents:
            return "Не нашёл подходящих SUMMARY-блоков в документации по этому запросу."
        lines = [context.documents[0].summary, "", "Файлы-источники:"]
        for item in context.documents:
            lines.append(f"- {item.path}")
        return "\n".join(lines)

    def trace_output(self, context: DocExplainSummaryContext) -> dict[str, object]:
        return {"answer_length": len(context.answer)}
