# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-tool-call-latency-from-token-accounting-latency-in-opentelemetry-genai-agent-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-tool-call-latency-from-token-accounting-latency-in-opentelemetry-genai-agent-spans.warrant.json
# Markdown SHA-256:   c498a2c6c3ad149298f8a9049c30007c832e53fc2b38444c3142b58fea0029ec
# Code AST SHA-256:   4cb30853a0723e768d1a83a0cf8c12238dff430abe8c987c0fbbc133710444b5
# Verified Classes:   TokenAccountingInvariantError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TokenAccountingInvariantError(RuntimeError):
    """Raised when an agent span's token rollup violates the GenAI convention invariant."""
    pass


def rollup_agent_tokens(chat_spans: list[dict]) -> dict:
    """
    chat_spans: list of dicts with keys:
      - 'input_tokens': int (provider-reported, cumulative prompt)
      - 'output_tokens': int (provider-reported, per-generation)
      - 'retry_count': int (0 for primary attempt)
    Returns billing-equivalent totals per GenAI semantic convention boundary.
    """
    if not chat_spans:
        raise TokenAccountingInvariantError(
            "cannot roll up tokens for an agent span with zero chat spans"
        )

    for span in chat_spans:
        if span.get("input_tokens", 0) < 0 or span.get("output_tokens", 0) < 0:
            raise TokenAccountingInvariantError(
                f"negative token count in span: {span!r}"
            )

    primary = [s for s in chat_spans if s.get("retry_count", 0) == 0]
    if not primary:
        raise TokenAccountingInvariantError(
            "all chat spans are retries; no primary invocation to anchor prompt cost"
        )

    # Output tokens are additive across generations.
    total_output = sum(s["output_tokens"] for s in chat_spans)

    # Input tokens are cumulative-on-prompt: take first prompt as base,
    # then add only the *delta* introduced by each subsequent step.
    ordered = sorted(primary, key=lambda s: s.get("step_index", 0))
    total_input = ordered[0]["input_tokens"]
    for prev, cur in zip(ordered, ordered[1:]):
        delta = cur["input_tokens"] - prev["input_tokens"]
        if delta < 0:
            # Prompt shrank between steps: context truncation or compaction.
            # Cannot attribute the delta; surface rather than silently clamp.
            raise TokenAccountingInvariantError(
                f"prompt shrank between steps ({prev['input_tokens']} -> "
                f"{cur['input_tokens']}); token rollup is undefined under compaction"
            )
        total_input += delta

    return {
        "input_tokens": total_input,
        "output_tokens": total_output,
        "total_tokens": total_input + total_output,
    }
