from __future__ import annotations

from typing import Generic, TypeVar

from app.core.agent.processes.v2.workflows.general_qa_summary.workflow_runtime.context_protocols import RetrievalWorkflowContext
from app.core.agent.utils.process_v2.rag_retrieval import V2RagRetrievalAdapter
from app.core.agent.utils.workflow import WorkflowStep

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


class FetchRagRowsStep(WorkflowStep[TContext], Generic[TContext]):
    step_id = "fetch_rag_rows"
    title = "Получение строк из RAG"

    def __init__(self, rag_adapter: V2RagRetrievalAdapter) -> None:
        self._rag_adapter = rag_adapter

    async def run(self, context: TContext) -> TContext:
        if context.answer or context.retrieval_plan is None:
            return context
        context.retrieved_rows = await self._rag_adapter.fetch_rows(
            context.rag_session_id,
            context.route.normalized_query,
            context.retrieval_plan,
        )
        return context

    def trace_output(self, context: TContext) -> dict[str, object]:
        return {"retrieved_row_count": len(context.retrieved_rows)}
