from __future__ import annotations

from typing import Generic, TypeVar

from app.core.agent.processes.v2.workflows.general_qa_summary.workflow_runtime.context_protocols import SummaryWorkflowContext
from app.core.agent.processes.v2.workflows.general_qa_summary.workflow_runtime.pipeline_logging import log_pipeline_step
from app.core.agent.utils.process_v2.evidence.gate import DocsEvidenceGate
from app.core.agent.utils.workflow import WorkflowStep

TContext = TypeVar("TContext", bound=SummaryWorkflowContext)


class ApplySummaryEvidenceGateStep(WorkflowStep[TContext], Generic[TContext]):
    step_id = "apply_summary_evidence_gate"
    title = "Проверка summary evidence"

    def __init__(self, gate: DocsEvidenceGate) -> None:
        self._gate = gate

    async def run(self, context: TContext) -> TContext:
        if context.answer:
            return context
        context.gate_decision = self._gate.check_summaries(context.route, context.documents)
        log_pipeline_step(
            context.runtime,
            "evidence_gate_checked",
            {
                "passed": context.gate_decision.passed,
                "reason": context.gate_decision.reason,
                "answer_mode": context.gate_decision.answer_mode,
            },
        )
        return context

    def trace_output(self, context: TContext) -> dict[str, object]:
        return {"passed": bool(context.gate_decision and context.gate_decision.passed)}
