# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-agent-span-the-tool-call-token-accounting-divergence-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-agent-span-the-tool-call-token-accounting-divergence-boundary.warrant.json
# Markdown SHA-256:   1b37fd8bc1c1223edab21e7223301dbb6b1d07673da83eaa3716b10c653979e5
# Code AST SHA-256:   4698f81ae81a0775fb6135984f132dd428e1bd0ad18911b253f07868b9c43932
# Verified Classes:   GenAITokenAccountingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class GenAITokenAccountingError(RuntimeError):
    """Raised when a span's token attributes cannot be soundly aggregated."""
    pass


MODEL_OPERATIONS = frozenset({"chat", "text_completion", "embeddings", "generate_content"})


def validate_usage_attribution(span: dict) -> None:
    """
    Enforce the GenAI usage-attribution invariant on a single span.

    A span may carry gen_ai.usage.* only if it represents a model invocation,
    or if it is a tool span that explicitly declares a nested model call.
    """
    attrs = span.get("attributes", {})
    op = attrs.get("gen_ai.operation.name")
    has_usage = any(k.startswith("gen_ai.usage.") for k in attrs)

    if not has_usage:
        return

    if op in MODEL_OPERATIONS:
        return

    # Tool span carrying usage: only legal if it self-declares a nested model call.
    if op == "execute_tool":
        if attrs.get("gen_ai.tool.nested_model_invocation") is True:
            return
        raise GenAITokenAccountingError(
            f"tool span {span.get('span_id')} carries gen_ai.usage.* without "
            f"nested_model_invocation marker; usage is likely copied from parent "
            f"and must not be summed."
        )

    raise GenAITokenAccountingError(
        f"span {span.get('span_id')} with operation {op!r} carries gen_ai.usage.* "
        f"but is not a model-invoking operation; refusing to emit."
    )


def aggregate_trace_usage(spans: list[dict]) -> dict[str, int]:
    """
    Sum token usage across a trace, partitioning by model-invoking span and
    de-duplicating by span_id. Raises if any span violates attribution.
    """
    seen: set[str] = set()
    totals = {"input_tokens": 0, "output_tokens": 0}

    for span in spans:
        validate_usage_attribution(span)
        op = span.get("attributes", {}).get("gen_ai.operation.name")
        if op not in MODEL_OPERATIONS and not (
            op == "execute_tool"
            and span.get("attributes", {}).get("gen_ai.tool.nested_model_invocation") is True
        ):
            continue
        sid = span["span_id"]
        if sid in seen:
            raise GenAITokenAccountingError(
                f"duplicate model-invoking span_id {sid} in trace; refusing to double-count."
            )
        seen.add(sid)
        a = span["attributes"]
        totals["input_tokens"] += int(a.get("gen_ai.usage.input_tokens", 0))
        totals["output_tokens"] += int(a.get("gen_ai.usage.output_tokens", 0))

    return totals
