from __future__ import annotations

from typing import Generic, TypeVar

from app.core.agent.processes.v2.workflows.doc_explain_summary.workflow_runtime.context_protocols import SummaryWorkflowContext
from app.core.agent.processes.v2.workflows.doc_explain_summary.workflow_runtime.pipeline_logging import log_pipeline_step, log_ranking
from app.core.agent.utils.process_v2.evidence.assembler import DocsEvidenceAssembler
from app.core.agent.utils.workflow import WorkflowStep

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


class BuildSummaryEvidenceStep(WorkflowStep[TContext], Generic[TContext]):
    step_id = "build_summary_evidence"
    title = "Сборка summary evidence"

    def __init__(self, assembler: DocsEvidenceAssembler) -> None:
        self._assembler = assembler

    async def run(self, context: TContext) -> TContext:
        if context.answer:
            return context
        context.documents = self._assembler.assemble_summaries(context.rows, context.route)
        context.runtime.trace.module("process.v2.evidence").log(
            "evidence_assembled",
            {
                "mode": "summary",
                "document_count": len(context.documents),
                "documents": [item.path for item in context.documents],
            },
        )
        log_pipeline_step(
            context.runtime,
            "evidence_assembled",
            {
                "mode": "summary",
                "primary_doc": context.documents[0].path if context.documents else None,
                "document_count": len(context.documents),
            },
        )
        log_ranking(context.runtime, context.documents)
        return context

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