"""Сборка финального результата пайплайна: диагностика и RuntimeFinalResult."""

from __future__ import annotations

import logging
from typing import Any

from app.modules.agent.runtime.steps.context.diagnostics import build_diagnostics_report
from app.modules.agent.runtime.steps.gates.post.post_gate import RuntimePostEvidenceGate, RuntimeValidationResult
from app.modules.agent.runtime.models import RuntimeDraftAnswer, RuntimeExecutionState, RuntimeFinalResult

LOGGER = logging.getLogger(__name__)


def assemble_final_result(
    state: RuntimeExecutionState,
    *,
    draft: RuntimeDraftAnswer | None,
    final_answer: str,
    repair_used: bool,
    llm_used: bool,
    validation: RuntimeValidationResult | None = None,
    timings_ms: dict[str, int] | None = None,
    runtime_trace: list[dict] | None = None,
    answer_policy_branch: str = "",
    decision_reason: str = "",
    pre_gate_input: dict[str, Any] | None = None,
    post_gate_snapshot: dict[str, Any] | None = None,
    resolved_target: str | None = None,
    post_gate: RuntimePostEvidenceGate | None = None,
) -> RuntimeFinalResult:
    diagnostics = build_diagnostics_report(
        router_result=state.router_result,
        retrieval_request=state.retrieval_request,
        retrieval_result=state.retrieval_result,
        evidence_bundle=state.evidence_pack,
        answer_mode=state.answer_mode,
        timings_ms=timings_ms or {},
        resolved_target=resolved_target,
        answer_policy_branch=answer_policy_branch,
        decision_reason=decision_reason,
        evidence_gate_input=pre_gate_input or {},
        post_evidence_gate=post_gate_snapshot or {},
    )
    if validation is None and post_gate is not None and state.retrieval_request is not None:
        validation = post_gate.validate(
            answer=final_answer,
            answer_mode=state.answer_mode,
            degraded_message=state.degraded_message,
            sub_intent=state.retrieval_request.sub_intent,
            user_query=state.user_query,
            evidence_pack=state.evidence_pack,
        )
    elif validation is None:
        validation = RuntimeValidationResult(passed=True, action="return")

    result = RuntimeFinalResult(
        final_answer=final_answer.strip(),
        answer_mode=state.answer_mode,
        repair_used=repair_used,
        llm_used=llm_used,
        draft_answer=draft,
        validation=validation,
        router_result=state.router_result,
        retrieval_request=state.retrieval_request,
        retrieval_result=state.retrieval_result,
        evidence_pack=state.evidence_pack,
        diagnostics=diagnostics,
        runtime_trace=list(runtime_trace or []),
    )
    LOGGER.warning(
        "agent runtime executed: intent=%s sub_intent=%s answer_mode=%s repair_used=%s llm_used=%s",
        state.router_result.intent if state.router_result else None,
        state.router_result.query_plan.sub_intent if state.router_result and state.router_result.query_plan else None,
        result.answer_mode,
        result.repair_used,
        result.llm_used,
    )
    return result
