# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-genai-tool-call-span-whose-token-accounting-is-split-across-a-parent-agent-envelope-and-a-child-tool-envel.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-genai-tool-call-span-whose-token-accounting-is-split-across-a-parent-agent-envelope-and-a-child-tool-envel.warrant.json
# Markdown SHA-256:   821dc67cbb7c95e6af3eeba4f09cd249dd22225736a8d5b3ba3bc90f846a1842
# Code AST SHA-256:   ca68baa5687b6fa950cc5fb1c0862af86aea4081bb0de14b8ec303cdd20a1529
# Verified Classes:   UsageAttributionError, SpanUsage
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class UsageAttributionError(RuntimeError):
    """Raised when a GenAI trace violates the single-attribution invariant."""


@dataclass(frozen=True)
class SpanUsage:
    span_id: str
    response_id: str | None
    input_tokens: int
    output_tokens: int
    is_tool_wrapper: bool


def validate_usage_partition(spans: list[SpanUsage]) -> dict[str, int]:
    """
    Enforce: each model response's usage appears on exactly one non-wrapper span.
    Returns the reconciled total. Raises on violation rather than aggregating.
    """
    seen: dict[str, str] = {}  # response_id -> span_id that owns the usage
    total_input = 0
    total_output = 0

    for s in spans:
        has_usage = s.input_tokens > 0 or s.output_tokens > 0
        if not has_usage:
            continue

        if s.is_tool_wrapper:
            raise UsageAttributionError(
                f"tool-wrapper span {s.span_id} carries gen_ai.usage.* "
                f"(input={s.input_tokens}, output={s.output_tokens}); "
                f"usage must live on the chat/invoke_agent span that hit the model"
            )

        if s.response_id is None:
            raise UsageAttributionError(
                f"span {s.span_id} carries usage but has no gen_ai.response.id; "
                f"cannot deduplicate or reconcile against provider billing"
            )

        if s.response_id in seen:
            raise UsageAttributionError(
                f"response {s.response_id} usage attributed twice: "
                f"already on span {seen[s.response_id]}, repeated on {s.span_id}"
            )

        seen[s.response_id] = s.span_id
        total_input += s.input_tokens
        total_output += s.output_tokens

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


def reconcile_or_reject(spans: list[SpanUsage], provider_input: int) -> dict[str, int]:
    totals = validate_usage_partition(spans)
    if totals["input_tokens"] != provider_input:
        raise UsageAttributionError(
            f"trace usage {totals['input_tokens']} != provider-reported "
            f"{provider_input}; partition invariant broken upstream"
        )
    return totals
