# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attributes-child-span-token-counts-to-the-parent-turn-double-counting-under-opentelemetry-genai-spans-and-the-per-span-s.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attributes-child-span-token-counts-to-the-parent-turn-double-counting-under-opentelemetry-genai-spans-and-the-per-span-s.warrant.json
# Markdown SHA-256:   669cc12eee71d37f99b9b54f27a8f5e9770e9265021e68a587fff8842256a64a
# Code AST SHA-256:   f116ac21722078218f71747aae86280a0a207a2b4d4b959fa674cfbc7559d9a0
# Verified Classes:   GenAIUsageAttributionError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class GenAIUsageAttributionError(RuntimeError):
    """Raised when a span violates the single-writer usage invariant."""


MODEL_OPERATIONS = {"chat", "text_completion", "embeddings", "generate_content"}
USAGE_KEYS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens")


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_id: str | None
    attributes: dict[str, Any] = field(default_factory=dict)

    @property
    def operation(self) -> str | None:
        return self.attributes.get("gen_ai.operation.name")

    @property
    def carries_usage(self) -> bool:
        return any(k in self.attributes for k in USAGE_KEYS)


def validate_usage_ownership(spans: list[Span]) -> None:
    """Enforce: only model-operation spans may carry gen_ai.usage.* attributes."""
    for span in spans:
        if not span.carries_usage:
            continue
        if span.operation not in MODEL_OPERATIONS:
            raise GenAIUsageAttributionError(
                f"span {span.span_id} (op={span.operation!r}) carries "
                f"gen_ai.usage.* but is not a model invocation; "
                f"turn-level totals must use a distinct namespace "
                f"(e.g. agent.turn.total_input_tokens)"
            )


def sum_trace_tokens(spans: list[Span], trace_id: str) -> int:
    """Sum input tokens for a trace, counting only owning model spans."""
    validate_usage_ownership([s for s in spans if s.trace_id == trace_id])
    total = 0
    for span in spans:
        if span.trace_id != trace_id:
            continue
        if span.operation in MODEL_OPERATIONS:
            total += int(span.attributes.get(USAGE_KEYS[0], 0))
    return total
