from __future__ import annotations

from app.core.agent.processes.v2.workflows.doc_explain_find_files.workflow_runtime.context import DocExplainFindFilesContext
from app.core.agent.utils.workflow import WorkflowStep


class FinalizeFindFilesAnswerStep(WorkflowStep[DocExplainFindFilesContext]):
    step_id = "finalize_find_files_answer"
    title = "Сборка списка файлов"

    async def run(self, context: DocExplainFindFilesContext) -> DocExplainFindFilesContext:
        if context.answer:
            return context
        if not context.files:
            context.answer = "Не нашёл файлов документации, которые уверенно соответствуют запросу."
            context.answer_generated_payload = {"answer_mode": "insufficient_evidence", "answer_length": len(context.answer)}
            return context
        if context.gate_decision is not None and context.gate_decision.reason == "low_confidence_shortlist":
            context.answer = "\n".join(item.path for item in context.files[:4])
            context.answer_generated_payload = {
                "answer_mode": context.gate_decision.answer_mode,
                "answer_length": len(context.answer),
            }
            return context
        if len(context.files) == 1:
            context.answer = context.files[0].path
            context.answer_generated_payload = {"answer_mode": "deterministic", "answer_length": len(context.answer)}
            return context
        context.answer = "\n".join(item.path for item in context.files[:4])
        context.answer_generated_payload = {"answer_mode": "deterministic", "answer_length": len(context.answer)}
        return context

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