# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-an-opentelemetry-genai-span-whose-gen-ai-usage-input-tokens-was-inherited-from-a-parent-agent-span-rathe.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-an-opentelemetry-genai-span-whose-gen-ai-usage-input-tokens-was-inherited-from-a-parent-agent-span-rathe.warrant.json
# Markdown SHA-256:   3ae7486aa44f8c4f28726487a5bd3316be4fb9d341dd4429c9b766c1a0302030
# Code AST SHA-256:   5fd37cc88f1d5288279173da2af8174468a89fa8c33e1f271ed260f94bd4406e
# Verified Classes:   UsageAdmissibilityError, UsageSource, SpanSnapshot
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class UsageAdmissibilityError(RuntimeError):
    """Raised when a gen_ai.usage.* attribute cannot be trusted as a control signal."""


class UsageSource(Enum):
    MEASURED = "measured"
    INHERITED = "inherited"
    ESTIMATED = "estimated"
    UNKNOWN = "unknown"


TOKEN_CONSUMING_OPS = {"chat", "text_completion", "embeddings", "generate_content"}


@dataclass
class SpanSnapshot:
    name: str
    attributes_at_creation: dict[str, Any]
    operation_name: str
    status_code: str = "UNSET"
    has_response_event: bool = False
    final_attributes: dict[str, Any] = field(default_factory=dict)


def classify_usage_source(snap: SpanSnapshot) -> UsageSource:
    """Determine whether gen_ai.usage.input_tokens on this span is measured or inherited."""
    key = "gen_ai.usage.input_tokens"
    creation_value = snap.attributes_at_creation.get(key)
    final_value = snap.final_attributes.get(key)

    if final_value is None:
        return UsageSource.UNKNOWN
    if creation_value is not None and creation_value == final_value:
        # Present at creation with the same value at end: never measured at boundary.
        return UsageSource.INHERITED
    if creation_value is not None and creation_value != final_value:
        # Pre-flight estimate overwritten by a measured value — measured if OK.
        if snap.status_code == "OK" and snap.has_response_event:
            return UsageSource.MEASURED
        return UsageSource.ESTIMATED
    # Absent at creation, present at end: written by the provider-response path.
    if snap.status_code == "OK" and snap.has_response_event:
        return UsageSource.MEASURED
    return UsageSource.ESTIMATED


def admissible_input_tokens(snap: SpanSnapshot) -> int:
    """Return the token count admissible for budget guards, or raise if not admissible."""
    source = classify_usage_source(snap)

    if source is UsageSource.INHERITED:
        raise UsageAdmissibilityError(
            f"span {snap.name!r}: gen_ai.usage.input_tokens was inherited from an "
            f"ancestor span and must not drive control decisions"
        )
    if source is UsageSource.ESTIMATED:
        raise UsageAdmissibilityError(
            f"span {snap.name!r}: gen_ai.usage.input_tokens is an estimate "
            f"(status={snap.status_code}, response_event={snap.has_response_event}); "
            f"cannot be trusted for budget enforcement"
        )
    if source is UsageSource.UNKNOWN:
        raise UsageAdmissibilityError(
            f"span {snap.name!r}: no gen_ai.usage.input_tokens present"
        )
    if snap.operation_name not in TOKEN_CONSUMING_OPS:
        raise UsageAdmissibilityError(
            f"span {snap.name!r}: operation {snap.operation_name!r} cannot consume "
            f"input tokens, yet carries a measured usage value"
        )

    return int(snap.final_attributes["gen_ai.usage.input_tokens"])


def enforce_budget(snap: SpanSnapshot, limit: int) -> None:
    """Budget guard that refuses to act on inherited or estimated usage."""
    try:
        used = admissible_input_tokens(snap)
    except UsageAdmissibilityError:
        # Quarantine: do not downgrade, do not aggregate. Let the call proceed
        # under the measured value once the response arrives.
        return
    if used > limit:
        raise UsageAdmissibilityError(
            f"span {snap.name!r}: measured input_tokens={used} exceeds limit={limit}"
        )
