from __future__ import annotations

from typing import Generic, TypeVar

from app.core.agent.processes.v2.workflows.doc_explain_api_exposed.steps.retrieval.api_endpoint_collector import (
    ApiEndpointCollector,
)
from app.core.agent.processes.v2.workflows.doc_explain_api_exposed.workflow_runtime.context_protocols import ApiWorkflowContext
from app.core.agent.processes.v2.workflows.doc_explain_api_exposed.workflow_runtime.pipeline_logging import log_pipeline_step
from app.core.agent.utils.workflow import WorkflowStep

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


class BuildApiExposedEvidenceStep(WorkflowStep[TContext], Generic[TContext]):
    step_id = "build_api_exposed_evidence"
    title = "Сборка списка API"

    def __init__(self, collector: ApiEndpointCollector) -> None:
        self._collector = collector

    async def run(self, context: TContext) -> TContext:
        if context.answer:
            return context
        context.endpoints = self._collector.collect(context.retrieved_rows)
        context.runtime.trace.module("process.v2.evidence").log(
            "evidence_assembled",
            {"mode": "api_exposed", "endpoint_count": len(context.endpoints), "endpoints": context.endpoints},
        )
        log_pipeline_step(
            context.runtime,
            "evidence_assembled",
            {"mode": "api_exposed", "endpoint_count": len(context.endpoints)},
        )
        return context

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

