# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-otel-genai-agent-spans-whose-tool-call-attributes-desynchronize-from-token-accounting-at-the-span-close-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-otel-genai-agent-spans-whose-tool-call-attributes-desynchronize-from-token-accounting-at-the-span-close-boundary.warrant.json
# Markdown SHA-256:   38f3bab6df75558e724f64706ecb6485c20fb6a697cfa0ff1e98de92317ca046
# Code AST SHA-256:   f38fc1d2d5c6f6b930bcfed552e3bf02c4254cfa9830306aec03ac306187acaf
# Verified Classes:   SpanReconciliationError, ChatTurn, ToolCall, AgentSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpanReconciliationError(RuntimeError):
    """Raised when an agent span is finalized with unreconciled tool/usage state."""


@dataclass
class ChatTurn:
    input_tokens: int
    output_tokens: int
    closed: bool


@dataclass
class ToolCall:
    call_id: str
    closed: bool
    abandoned: bool = False


@dataclass
class AgentSpan:
    name: str
    turns: list[ChatTurn] = field(default_factory=list)
    tools: list[ToolCall] = field(default_factory=list)

    def total_usage(self) -> tuple[int, int]:
        inp = sum(t.input_tokens for t in self.turns if t.closed)
        out = sum(t.output_tokens for t in self.turns if t.closed)
        return inp, out

    def finalize(self, *, strict: bool = True) -> dict:
        open_tools = [t for t in self.tools if not t.closed and not t.abandoned]
        open_turns = [t for t in self.turns if not t.closed]
        inp, out = self.total_usage()

        if open_tools or open_turns:
            if strict:
                raise SpanReconciliationError(
                    f"agent span {self.name!r} finalized with "
                    f"{len(open_tools)} open tool span(s) "
                    f"{[t.call_id for t in open_tools]} and "
                    f"{len(open_turns)} unclosed chat turn(s); "
                    f"recorded usage would undercount in-flight calls"
                )
            # Non-strict: label the incompleteness instead of silently undercounting.
            return {
                "span": self.name,
                "gen_ai.usage.input_tokens": inp,
                "gen_ai.usage.output_tokens": out,
                "gen_ai.usage.reconciliation": "incomplete",
                "pending_tool_calls": len(open_tools),
                "pending_turns": len(open_turns),
            }

        return {
            "span": self.name,
            "gen_ai.usage.input_tokens": inp,
            "gen_ai.usage.output_tokens": out,
            "gen_ai.usage.reconciliation": "complete",
        }


def close_agent_span(span: AgentSpan, *, budget_expired: bool) -> dict:
    if budget_expired:
        # Force-close children as abandoned so they cannot orphan post-export.
        for tool in span.tools:
            if not tool.closed:
                tool.abandoned = True
        for turn in span.turns:
            if not turn.closed:
                # In-flight turn: cost is spent at the provider but unknown here.
                turn.closed = True  # mark terminal, but usage stays 0
                turn.input_tokens = -1  # sentinel: unknown-but-spent
        try:
            return span.finalize(strict=True)
        except SpanReconciliationError as exc:
            # Re-raise with context: this is the boundary we refuse to cross silently.
            raise SpanReconciliationError(
                f"cannot reconcile {span.name!r} at budget boundary: {exc}"
            ) from exc
    return span.finalize(strict=True)
