# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-gen-ai-usage-token-count-for-a-tool-call-span-whose-payload-it-never-fully-observed.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-gen-ai-usage-token-count-for-a-tool-call-span-whose-payload-it-never-fully-observed.warrant.json
# Markdown SHA-256:   709c443dafd0a05e1677cfac096e7e91730ae18ebbf724a0c2367d8cc74daa25
# Code AST SHA-256:   4e5c740c7522fe0d81d4ed8fa4089ff8863640e8f764c539ca05d2bb4a7c08ea
# Verified Classes:   UnmeasuredUsageError, GenAiSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnmeasuredUsageError(RuntimeError):
    """Raised when a span attempts to emit a measured gen_ai.usage attribute
    without having consumed the provider's terminal usage event."""
    pass


@dataclass
class GenAiSpan:
    name: str
    operation: str
    usage_terminal_seen: bool = False
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    attributes: dict = field(default_factory=dict)

    def on_usage_event(self, kind: str, tokens: int) -> None:
        # 'message_start' carries input; 'message_delta' is the terminal output event.
        if kind == "message_start":
            self.input_tokens = tokens
        elif kind == "message_delta":
            self.output_tokens = tokens
            self.usage_terminal_seen = True
        else:
            raise UnmeasuredUsageError(f"unknown usage event kind: {kind}")

    def close(self, cancelled: bool) -> None:
        if self.input_tokens is not None:
            self.attributes["gen_ai.usage.input_tokens"] = self.input_tokens

        if self.output_tokens is not None and self.usage_terminal_seen:
            self.attributes["gen_ai.usage.output_tokens"] = self.output_tokens
        elif cancelled and not self.usage_terminal_seen:
            # Refuse to forge a measured output count. Emit a marked estimate
            # under a distinct key so measured-key consumers never see it.
            if self.output_tokens is not None:
                self.attributes["gen_ai.usage.estimated_output_tokens"] = self.output_tokens
                self.attributes["gen_ai.usage.source"] = "local_tokenizer"
            # Deliberately omit gen_ai.usage.output_tokens.
        else:
            raise UnmeasuredUsageError(
                f"span {self.name!r} closed without terminal usage event "
                f"and without a cancellation justification; cannot emit "
                f"measured output_tokens"
            )


def emit_span(span: GenAiSpan, *, cancelled: bool) -> dict:
    span.close(cancelled=cancelled)
    if "gen_ai.usage.output_tokens" in span.attributes and not span.usage_terminal_seen:
        # Defensive invariant check: measured key must imply measurement.
        raise UnmeasuredUsageError(
            f"invariant violated on span {span.name!r}: measured output_tokens "
            f"present without usage_terminal_seen"
        )
    return span.attributes
