from __future__ import annotations

from typing import Generic, TypeVar

from app.core.agent.processes.v2.workflows.doc_explain_summary.workflow_runtime.context_protocols import RetrievalWorkflowContext
from app.core.agent.processes.v2.workflows.doc_explain_summary.workflow_runtime.pipeline_logging import log_pipeline_step
from app.core.agent.utils.process_v2.evidence.gate import EvidenceGateDecision
from app.core.agent.utils.workflow import WorkflowStep

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


class RequireRagSessionStep(WorkflowStep[TContext], Generic[TContext]):
    step_id = "require_rag_session"
    title = "Проверка RAG-сессии"

    def __init__(self, *, missing_message: str, missing_gate: EvidenceGateDecision | None = None) -> None:
        self._missing_message = missing_message
        self._missing_gate = missing_gate

    async def run(self, context: TContext) -> TContext:
        if context.rag_session_id:
            return context
        context.answer = self._missing_message
        if self._missing_gate is not None:
            context.gate_decision = self._missing_gate
            context.answer_generated_payload = {
                "answer_mode": self._missing_gate.answer_mode,
                "answer_length": len(context.answer),
            }
            log_pipeline_step(
                context.runtime,
                "evidence_gate_checked",
                {
                    "passed": self._missing_gate.passed,
                    "reason": self._missing_gate.reason,
                    "answer_mode": self._missing_gate.answer_mode,
                },
            )
        return context

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