# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-close-an-opentelemetry-agent-span-when-genai-token-attributes-are-non-additive-across-tool-call-retries.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-close-an-opentelemetry-agent-span-when-genai-token-attributes-are-non-additive-across-tool-call-retries.warrant.json
# Markdown SHA-256:   cb01e0901ed308eb410100d0dd42fe89b5b2ee40cd77b0f9cae5432b909c4574
# Code AST SHA-256:   b4884e4c9f9ad5e652022162c7cea20d6e7f6938af757a78b9d3cc771d46f683
# Verified Classes:   SpanAccountingError, FinishReason, ChildSpan, AgentSpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class SpanAccountingError(RuntimeError):
    """Raised when an agent span cannot be closed with a valid token sum."""


class FinishReason(str, Enum):
    STOP = "stop"
    LENGTH = "length"
    ABORTED = "aborted"
    ERROR = "error"


@dataclass
class ChildSpan:
    name: str
    input_tokens: int = 0
    output_tokens: int = 0
    cache_read_input_tokens: int = 0
    status: str = "OK"  # "OK" | "ERROR"
    finish_reasons: tuple[FinishReason, ...] = ()
    retried: bool = False


@dataclass
class AgentSpan:
    name: str
    children: list[ChildSpan] = field(default_factory=list)
    ledger_input_tokens: int | None = None  # ground truth, if available

    def _naive_input_sum(self) -> int:
        # Naive sum: what a span processor would compute by default.
        return sum(c.input_tokens for c in self.children)

    def _billed_input_estimate(self) -> int:
        # Best-effort: drop aborted streams, subtract cache reads.
        total = 0
        for c in self.children:
            if FinishReason.ABORTED in c.finish_reasons:
                continue
            total += c.input_tokens - c.cache_read_input_tokens
        return total

    def close(self) -> dict[str, object]:
        has_error_child = any(c.status == "ERROR" for c in self.children)
        has_aborted_child = any(
            FinishReason.ABORTED in c.finish_reasons for c in self.children
        )
        has_retry = any(c.retried for c in self.children)

        naive = self._naive_input_sum()
        estimate = self._billed_input_estimate()

        # Guardrail: refuse to close as OK with a populated sum when the
        # subtree contains an errored, aborted, or retried child and no
        # ledger reconciliation has been recorded.
        if (has_error_child or has_aborted_child or has_retry) and self.ledger_input_tokens is None:
            raise SpanAccountingError(
                f"agent span {self.name!r} has retried/errored/aborted children "
                f"(error={has_error_child}, aborted={has_aborted_child}, "
                f"retry={has_retry}) and no ledger reconciliation; "
                f"naive_sum={naive} vs billed_estimate={estimate}"
            )

        if self.ledger_input_tokens is not None and naive != self.ledger_input_tokens:
            # Reconciliation mismatch: emit but tag, do not silently pass.
            return {
                "gen_ai.usage.input_tokens": self.ledger_input_tokens,
                "gen_ai.usage.reconciliation_status": "MISMATCH",
                "gen_ai.usage.naive_sum": naive,
            }

        return {
            "gen_ai.usage.input_tokens": self.ledger_input_tokens
            if self.ledger_input_tokens is not None
            else estimate,
            "gen_ai.usage.reconciliation_status": "OK"
            if self.ledger_input_tokens is not None
            else "UNRECONCILED",
        }


def emit_agent_turn(span: AgentSpan) -> dict[str, object]:
    return span.close()
