# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-when-a-streaming-tool-call-span-terminates-before-its-final-usage-chunk-ar.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-when-a-streaming-tool-call-span-terminates-before-its-final-usage-chunk-ar.warrant.json
# Markdown SHA-256:   72c934de143ec87aeca6a3a66d78c70396217e1798f2269038be1293ff50702d
# Code AST SHA-256:   b299f7f1c0b40f50b067dfebe478f6489342b1ca2de599ad4ccc53dc1ea3731f
# Verified Classes:   UsageReconciliationError, StreamOutcome, SpanStatus, GenAIChatSpan
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class UsageReconciliationError(RuntimeError):
    """Raised when a GenAI chat span cannot be reconciled to a usage record."""


class StreamOutcome(Enum):
    COMPLETE = "complete"          # terminal usage frame received
    ABORTED_LOCAL = "aborted_local"  # consumer closed; local counter valid
    ABORTED_UNKNOWN = "aborted_unknown"  # consumer closed; no counter


class SpanStatus(Enum):
    OK = "OK"
    ERROR = "ERROR"
    UNSET = "UNSET"


@dataclass
class GenAIChatSpan:
    trace_id: str
    span_id: str
    model: str
    outcome: StreamOutcome
    terminal_usage: Optional[dict] = None      # from provider final frame
    local_output_count: Optional[int] = None   # runtime incremental counter
    finish_reason: Optional[str] = None
    attributes: dict = field(default_factory=dict)

    def close(self) -> "GenAIChatSpan":
        """Apply the reconciliation invariant at span close."""
        if self.outcome is StreamOutcome.COMPLETE:
            if not self.terminal_usage:
                # Terminal frame claimed complete but carried no usage.
                raise UsageReconciliationError(
                    f"span {self.span_id}: COMPLETE outcome without terminal usage frame"
                )
            self.attributes["gen_ai.usage.input_tokens"] = self.terminal_usage["input_tokens"]
            self.attributes["gen_ai.usage.output_tokens"] = self.terminal_usage["output_tokens"]
            self.attributes["gen_ai.usage.provenance"] = "provider_terminal"
            self.attributes["gen_ai.response.finish_reasons"] = [self.finish_reason or "stop"]
            self.attributes["otel.status_code"] = SpanStatus.OK.value
            return self

        if self.outcome is StreamOutcome.ABORTED_LOCAL:
            if self.local_output_count is None:
                raise UsageReconciliationError(
                    f"span {self.span_id}: ABORTED_LOCAL without local counter"
                )
            # Input tokens are unmeasurable post-abort; record as unknown, not zero.
            self.attributes["gen_ai.usage.output_tokens"] = self.local_output_count
            self.attributes["gen_ai.usage.input_tokens"] = None  # explicit unknown
            self.attributes["gen_ai.usage.provenance"] = "local_incremental"
            self.attributes["gen_ai.response.finish_reasons"] = ["aborted"]
            # Aborted stream is NOT OK: the invocation did not complete.
            self.attributes["otel.status_code"] = SpanStatus.ERROR.value
            return self

        if self.outcome is StreamOutcome.ABORTED_UNKNOWN:
            # Emit no usage attributes; mark provenance so pipeline sees typed absence.
            self.attributes["gen_ai.usage.provenance"] = "unavailable"
            self.attributes["gen_ai.response.finish_reasons"] = ["aborted"]
            self.attributes["otel.status_code"] = SpanStatus.ERROR.value
            return self

        raise UsageReconciliationError(
            f"span {self.span_id}: unhandled outcome {self.outcome!r}"
        )


def validate_accounting_unit(span: GenAIChatSpan) -> None:
    """Invariant: every OK chat span carries a provider-terminal usage record."""
    status = span.attributes.get("otel.status_code")
    provenance = span.attributes.get("gen_ai.usage.provenance")
    if status == SpanStatus.OK.value:
        if provenance != "provider_terminal":
            raise UsageReconciliationError(
                f"span {span.span_id}: OK status with provenance {provenance!r}; "
                "an OK chat span must carry provider-terminal usage"
            )
        if span.attributes.get("gen_ai.usage.output_tokens") is None:
            raise UsageReconciliationError(
                f"span {span.span_id}: OK status with null output_tokens"
            )
    else:
        # Non-OK spans must carry an explicit provenance marker, never silent absence.
        if provenance is None:
            raise UsageReconciliationError(
                f"span {span.span_id}: non-OK status without usage provenance marker"
            )


def reconcile(session_spans: list[GenAIChatSpan], session_ceiling: int) -> int:
    """Recompute session consumption; refuse to admit if telemetry under-counts."""
    total = 0
    for span in session_spans:
        validate_accounting_unit(span)
        out = span.attributes.get("gen_ai.usage.output_tokens")
        if out is not None:
            total += out
        elif span.attributes.get("gen_ai.usage.provenance") == "unavailable":
            # Cannot cost this span; fail closed rather than under-count.
            raise UsageReconciliationError(
                f"span {span.span_id}: usage unavailable; session accounting incomplete"
            )
    if total > session_ceiling:
        raise UsageReconciliationError(
            f"session over ceiling: {total} > {session_ceiling}"
        )
    return total
