# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-in-its-own-opentelemetry-genai-spans-when-tool-call-token-accounting-silently-double-counts-acro.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-in-its-own-opentelemetry-genai-spans-when-tool-call-token-accounting-silently-double-counts-acro.warrant.json
# Markdown SHA-256:   c856a041bc209a1c64868d31d3c5121fd21ba724dfb5cd76e87db849ae564342
# Code AST SHA-256:   813b4270dac20fd811946a005250670c72a453046a18f0c62b53dd8c83088b80
# Verified Classes:   TokenAccountingAmbiguity, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TokenAccountingAmbiguity(RuntimeError):
    """Raised when a span's gen_ai.usage.* provenance (self vs subtree) is undecidable."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    input_tokens: int | None
    output_tokens: int | None
    children: list["Span"] = field(default_factory=list)


def _child_token_sum(span: Span) -> tuple[int, int]:
    ci = sum(c.input_tokens or 0 for c in span.children)
    co = sum(c.output_tokens or 0 for c in span.children)
    return ci, co


def recover_self_usage(span: Span, present_ids: set[str]) -> tuple[int, int]:
    """
    Return (self_input, self_output) for a token-bearing span.
    Detects mixed aggregator spans and refuses when descendants are missing.
    """
    if span.input_tokens is None and span.output_tokens is None:
        return 0, 0

    token_children = [c for c in span.children
                      if c.input_tokens is not None or c.output_tokens is not None]

    if not token_children:
        return span.input_tokens or 0, span.output_tokens or 0

    # Descendants referenced but not present in the batch -> provenance undecidable.
    missing = [c.span_id for c in token_children if c.span_id not in present_ids]
    if missing:
        raise TokenAccountingAmbiguity(
            f"span {span.span_id} is token-bearing with {len(token_children)} "
            f"token children, but {len(missing)} are absent from the batch "
            f"({missing[:3]}). self-vs-subtree provenance undecidable; refusing to sum."
        )

    ci, co = _child_token_sum(span)
    self_i = (span.input_tokens or 0) - ci
    self_o = (span.output_tokens or 0) - co

    if self_i < 0 or self_o < 0:
        raise TokenAccountingAmbiguity(
            f"span {span.span_id} reports less usage than its children "
            f"(self_input={self_i}, self_output={self_o}); truncated or re-emitted span."
        )
    return self_i, self_o


def total_billable_usage(spans: list[Span]) -> tuple[int, int]:
    """Sum recovered self-usage across the whole tree (cost attribution)."""
    present = {s.span_id for s in spans}
    ti = to = 0
    for s in spans:
        si, so = recover_self_usage(s, present)
        ti += si
        to += so
    return ti, to


def root_aggregated_usage(root: Span) -> tuple[int, int]:
    """Budget enforcement reads ONLY the root; never re-sums descendants."""
    if root.input_tokens is None and root.output_tokens is None:
        raise TokenAccountingAmbiguity(
            f"root span {root.span_id} carries no gen_ai.usage.*; cannot enforce budget."
        )
    return root.input_tokens or 0, root.output_tokens or 0
