# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-token-accounting-as-non-authoritative-across-agent-spans-and-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-token-accounting-as-non-authoritative-across-agent-spans-and-tool-calls.warrant.json
# Markdown SHA-256:   b115862ccd107838088708d0274e919ce4aaae6c837a1e8b0ac6eac82f5c5611
# Code AST SHA-256:   cffe23c15dd8ba624ba8dad82165e63432e993b5e9011696be3630bafdb27a8e
# Verified Classes:   NonAuthoritativeUsageError, SpanUsage, TraceUsage
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class NonAuthoritativeUsageError(RuntimeError):
    """Raised when aggregated GenAI token usage is used for a consequential action
    without a proof that the trace topology makes the aggregate additive."""


@dataclass
class SpanUsage:
    span_id: str
    kind: str  # "model" | "tool" | "wrapper"
    input_tokens: int = 0
    output_tokens: int = 0
    is_retry: bool = False
    is_wrapper_reaggregation: bool = False
    cache_read_tokens: int | None = None


@dataclass
class TraceUsage:
    spans: list[SpanUsage] = field(default_factory=list)

    def aggregate_naive(self) -> tuple[int, int]:
        return (
            sum(s.input_tokens for s in self.spans),
            sum(s.output_tokens for s in self.spans),
        )

    def assert_authoritative_for_billing(self) -> None:
        """Guard consequential use of the aggregate. Raises unless conditions hold."""
        reasons: list[str] = []
        if any(s.is_retry for s in self.spans):
            reasons.append("retry spans present: input re-billed, output single-counted")
        if any(s.is_wrapper_reaggregation for s in self.spans):
            reasons.append("wrapper span re-reports child usage: double-count risk")
        model_spans = [s for s in self.spans if s.kind == "model"]
        if len(model_spans) > 1 and not all(
            s.cache_read_tokens is not None for s in model_spans
        ):
            reasons.append(
                "multi-turn loop without cache-read attributes: prefix re-billing "
                "cannot be separated from genuine growth"
            )
        if any(s.kind == "tool" and (s.input_tokens or s.output_tokens) for s in self.spans):
            reasons.append("tool span carries model token usage: attribution is ambiguous")

        if reasons:
            raise NonAuthoritativeUsageError(
                "trace-aggregated gen_ai.usage is non-authoritative for billing: "
                + "; ".join(reasons)
            )


def record_chargeback(trace: TraceUsage, tenant: str) -> dict[str, int]:
    trace.assert_authoritative_for_billing()
    inp, out = trace.aggregate_naive()
    return {"tenant": tenant, "input_tokens": inp, "output_tokens": out}
