# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-emit-a-terminal-gen-ai-agent-span-event-before-its-child-tool-spans-close-and-why-token-accounting-silently-corrupts-when-it-doe.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-emit-a-terminal-gen-ai-agent-span-event-before-its-child-tool-spans-close-and-why-token-accounting-silently-corrupts-when-it-doe.warrant.json
# Markdown SHA-256:   1a2eaa05fbc86ed942773c2a812a9685d110f79a6dffe39e3e3a0b9049a3367a
# Code AST SHA-256:   b1788335717b0e9c0940555dd6bcbb4ace62c5272dd3e45dde2e5d864bd07bdc
# Verified Classes:   TerminalBeforeDrainError, SpanHandle, AgentSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class TerminalBeforeDrainError(RuntimeError):
    """Raised when an agent span attempts to emit its terminal event while child spans remain open."""
    pass


@dataclass
class SpanHandle:
    span_id: str
    kind: str  # "chat" | "tool"
    end_time: float | None = None
    usage_output_tokens: int = 0
    cancelled: bool = False

    def is_open(self) -> bool:
        return self.end_time is None and not self.cancelled


@dataclass
class AgentSpan:
    span_id: str
    open_children: dict[str, SpanHandle] = field(default_factory=dict)
    terminal_emitted: bool = False
    aggregate_output_tokens: int = 0

    def open_child(self, handle: SpanHandle) -> None:
        if self.terminal_emitted:
            # A child opened under a finalized parent can never be rolled up.
            raise TerminalBeforeDrainError(
                f"parent {self.span_id} already terminal; child {handle.span_id} would be orphaned from rollup"
            )
        self.open_children[handle.span_id] = handle

    def close_child(self, span_id: str, output_tokens: int, cancelled: bool = False) -> None:
        h = self.open_children[span_id]
        h.end_time = time.monotonic()
        h.cancelled = cancelled
        h.usage_output_tokens = 0 if cancelled else output_tokens

    def _drain(self, deadline_s: float) -> None:
        """Cancel any still-open child so it closes as a span before terminal emission."""
        start = time.monotonic()
        for h in list(self.open_children.values()):
            if h.is_open():
                if time.monotonic() - start > deadline_s:
                    # Deadline exceeded: cancel (a span-close), do not abandon.
                    self.close_child(h.span_id, output_tokens=0, cancelled=True)
                else:
                    raise TerminalBeforeDrainError(
                        f"child {h.span_id} still open at terminal emission for parent {self.span_id}"
                    )

    def emit_terminal(self, status: str, deadline_s: float = 0.0) -> int:
        if self.terminal_emitted:
            raise TerminalBeforeDrainError(f"parent {self.span_id} emitted terminal event twice")
        self._drain(deadline_s)
        self.aggregate_output_tokens = sum(h.usage_output_tokens for h in self.open_children.values())
        self.terminal_emitted = True
        return self.aggregate_output_tokens


def run_agent_step(agent: AgentSpan, tool_tokens: int, await_tool: bool) -> int:
    """Simulate a controller step. Non-awaited tools must be detached, not left open under the parent."""
    tool = SpanHandle(span_id="tool-1", kind="tool")
    agent.open_child(tool)
    if await_tool:
        agent.close_child(tool.span_id, output_tokens=tool_tokens)
    else:
        # Fire-and-forget: detach to a separate root, or the drain barrier will (correctly) refuse.
        agent.open_children.pop(tool.span_id)
    return agent.emit_terminal(status="completed", deadline_s=0.0)
