# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-double-counting-of-tokens-across-nested-agent-and-tool-spans-in-opentelemetry-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-double-counting-of-tokens-across-nested-agent-and-tool-spans-in-opentelemetry-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   d9d2ecc21cb0121f8c834fbd89e8f6ae059586d9075af39dad54063d07d30bc1
# Code AST SHA-256:   5d1ab3bdf0c37e553823a6bb747d39eb2f2117d6e26d939aa6e8ac17242466a9
# Verified Classes:   TokenAccountingInvariantError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a GenAI trace violates the non-additivity invariant for
    gen_ai.usage.* attributes across nested agent and model-operation spans."""


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    operation_name: str          # e.g. "invoke_agent", "chat", "execute_tool"
    input_tokens: int | None     # gen_ai.usage.input_tokens
    output_tokens: int | None    # gen_ai.usage.output_tokens


MODEL_OPS = {"chat", "text_completion", "embeddings"}
AGENT_OPS = {"invoke_agent", "create_agent"}


def billable_input_tokens(spans: list[Span]) -> int:
    """Sum input tokens using leaf-model-operation attribution.

    Raises TokenAccountingInvariantError if the trace exhibits double-recording
    (an agent span whose usage is duplicated by a model-operation descendant),
    or if usage appears on a non-model, non-agent span.
    """
    by_id = {s.span_id: s for s in spans}

    def ancestors(span: Span):
        cur = by_id.get(span.parent_id) if span.parent_id else None
        while cur is not None:
            yield cur
            cur = by_id.get(cur.parent_id) if cur.parent_id else None

    total = 0
    for span in spans:
        if span.input_tokens is None:
            continue

        if span.operation_name in MODEL_OPS:
            # A model op is always the accounting point for its own call.
            total += span.input_tokens

        elif span.operation_name in AGENT_OPS:
            model_descendants = [
                d for d in spans
                if d.operation_name in MODEL_OPS and span in set(ancestors(d))
            ]
            duplicates = [
                d for d in model_descendants
                if d.input_tokens == span.input_tokens
                and d.output_tokens == span.output_tokens
            ]
            if duplicates:
                # The agent span re-records a child model call. Do not add it;
                # the child already carries the usage.
                continue
            if model_descendants:
                raise TokenAccountingInvariantError(
                    f"agent span {span.span_id} carries usage but has "
                    f"model-operation descendants with differing usage; "
                    f"cannot determine whether its usage is local or aggregate"
                )
            # Agent span is the sole attribution point for its model call.
            total += span.input_tokens

        else:
            raise TokenAccountingInvariantError(
                f"span {span.span_id} (op={span.operation_name}) carries "
                f"gen_ai.usage.input_tokens; only model and agent operations "
                f"may record token usage"
            )

    return total
