from __future__ import annotations

from typing import Generic, TypeVar

from app.core.agent.processes.v2.workflows.doc_explain_api_exposed.workflow_runtime.context_protocols import RetrievalWorkflowContext
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) -> None:
        self._missing_message = missing_message

    async def run(self, context: TContext) -> TContext:
        if context.rag_session_id:
            return context
        context.answer = self._missing_message
        context.answer_generated_payload = {
            "answer_mode": "insufficient_evidence",
            "answer_length": len(context.answer),
        }
        return context

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

