# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-accounting-when-streaming-tool-call-spans-and-final-usage-records-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-accounting-when-streaming-tool-call-spans-and-final-usage-records-disagree.warrant.json
# Markdown SHA-256:   d509839d6ca70d7c4f7c7304f8a94f12f02f12842642686239df730a30cf0062
# Code AST SHA-256:   2b1a95c3682fc5988ef392c5c5cb58078012be2c92d9c9827d7b106e8d08fa69
# Verified Classes:   TokenAccountingError, UsageSource, GenAiChatSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class TokenAccountingError(RuntimeError):
    """Raised when a gen_ai.usage attribute would be written without provenance."""


class UsageSource(Enum):
    PROVIDER_REPORTED = "provider_reported"
    LOCAL_ESTIMATE = "local_estimate"


@dataclass
class GenAiChatSpan:
    name: str = "gen_ai.chat"
    attributes: dict = field(default_factory=dict)
    _closed: bool = False
    _usage_source: UsageSource | None = None

    def set_usage(self, input_tokens: int, output_tokens: int, source: UsageSource) -> None:
        if self._closed:
            # Writing usage after close loses the value in most exporters and,
            # worse, leaves the prior estimate in place with no marker.
            raise TokenAccountingError(
                f"span {self.name!r} already closed; cannot set usage from {source.value}"
            )
        if self._usage_source is not None and self._usage_source != source:
            raise TokenAccountingError(
                f"span {self.name!r} usage already set from {self._usage_source.value}, "
                f"refusing to overwrite from {source.value} without a correction event"
            )
        self.attributes["gen_ai.usage.input_tokens"] = input_tokens
        self.attributes["gen_ai.usage.output_tokens"] = output_tokens
        self.attributes["gen_ai.usage.source"] = source.value
        self._usage_source = source

    def close(self) -> None:
        if self._usage_source is None:
            # A closed span with no usage source is an unmarked estimate.
            raise TokenAccountingError(
                f"span {self.name!r} closed without a usage source marker"
            )
        self._closed = True


def finalize_streamed_turn(
    span: GenAiChatSpan,
    local_output_tokens: int,
    terminal_usage: dict | None,
    aborted: bool,
) -> GenAiChatSpan:
    if aborted or terminal_usage is None:
        # No authoritative count: record the estimate, but mark it as such.
        span.set_usage(
            input_tokens=terminal_usage["prompt_tokens"] if terminal_usage else 0,
            output_tokens=local_output_tokens,
            source=UsageSource.LOCAL_ESTIMATE,
        )
    else:
        # Reconcile-then-close: authoritative count wins, provenance recorded.
        span.set_usage(
            input_tokens=terminal_usage["prompt_tokens"],
            output_tokens=terminal_usage["completion_tokens"],
            source=UsageSource.PROVIDER_REPORTED,
        )
    span.close()
    return span
