# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-gen-ai-usage-input-tokens-on-an-agent-span-as-non-authoritative-for-cost-accounting.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-gen-ai-usage-input-tokens-on-an-agent-span-as-non-authoritative-for-cost-accounting.warrant.json
# Markdown SHA-256:   b623cd562e3cfc2a1b0abb4ac83ba8687dd63165dc2e2d243c30587f492cbb85
# Code AST SHA-256:   73788b2a24d793321b056286a21735bc94e75a92225f1383ea82ffc21dd0bc98
# Verified Classes:   TokenAccountingInvariantError, EmitterPolicy
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a trace's token attributes cannot be trusted for cost."""


@dataclass(frozen=True)
class EmitterPolicy:
    rolls_up_usage: bool          # invoke_agent span includes child chat usage
    always_on_sampling: bool
    wraps_tool_llm_calls: bool    # every in-tool LLM call emits a chat span
    reports_cache_reads_separately: bool


def cost_authoritative_tokens(
    spans: list[dict],
    policy: EmitterPolicy,
    *,
    provider_billed_tokens: int | None = None,
    tolerance: float = 0.15,
) -> int:
    """Return leaf-chat token sum, or raise if the trace cannot support cost use."""
    if not policy.always_on_sampling:
        raise TokenAccountingInvariantError(
            "sampled trace: token sums are a sample, not a ledger"
        )
    if not policy.wraps_tool_llm_calls:
        raise TokenAccountingInvariantError(
            "tool-internal LLM calls lack chat spans; tokens are invisible"
        )
    if not policy.reports_cache_reads_separately:
        raise TokenAccountingInvariantError(
            "cache reads not separated; input_tokens understates billed input"
        )

    leaf_chat = [
        s for s in spans
        if s.get("name") == "chat" and s.get("parent_kind") != "chat"
    ]
    if policy.rolls_up_usage:
        # Root already includes children; summing would double-count.
        roots = [s for s in spans if s.get("name") == "invoke_agent"]
        if len(roots) != 1:
            raise TokenAccountingInvariantError(
                f"roll-up emitter but {len(roots)} invoke_agent roots"
            )
        total = roots[0]["gen_ai.usage.input_tokens"]
    else:
        total = sum(s["gen_ai.usage.input_tokens"] for s in leaf_chat)

    if provider_billed_tokens is not None:
        delta = abs(total - provider_billed_tokens) / max(provider_billed_tokens, 1)
        if delta > tolerance:
            raise TokenAccountingInvariantError(
                f"trace total {total} vs billed {provider_billed_tokens} "
                f"delta {delta:.0%} exceeds {tolerance:.0%}; emitter policy drifted"
            )
    return total
