"""Граф workflow doc-explain summary: буфер шагов и один сброс в trace (на базе utils.workflow)."""

from __future__ import annotations

from typing import TypeVar

from app.core.agent.utils.workflow.context import WorkflowContext
from app.core.agent.utils.workflow.graph import WorkflowGraph

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


class DocExplainSummaryWorkflowGraph(WorkflowGraph[TContext]):
    """Не логирует step_started/step_completed по отдельности; сбрасывает буфер в ``workflow_trace_flushed``."""

    async def run(self, context: TContext) -> TContext:
        trace = context.runtime.trace.module(self._source)
        trace.log("workflow_started", {"workflow_id": self._workflow_id})
        steps_buffer: list[dict[str, object]] = []
        for step in self._steps:
            inp = step.trace_input(context)
            request_id = context.runtime.request.request_id
            await context.runtime.publisher.publish_status(
                request_id,
                self._source,
                f"Шаг workflow: {step.title}.",
                {"workflow_id": self._workflow_id, "step_id": step.step_id},
            )
            context = await step.run(context)
            out = step.trace_output(context)
            trace.log(
                "workflow_step_traced",
                {
                    "workflow_id": self._workflow_id,
                    "step": {"id": step.step_id, "title": step.title},
                    "input": inp,
                    "output": out,
                },
            )
            steps_buffer.append({"step_id": step.step_id, "title": step.title, "input": inp, "output": out})
        trace.log(
            "workflow_trace_flushed",
            {"workflow_id": self._workflow_id, "steps": steps_buffer},
        )
        trace.log("workflow_completed", {"workflow_id": self._workflow_id})
        return context
