# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-gen-ai-usage-attributes-as-non-authoritative-when-a-tool-call-event-stream-is-truncated-m.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-gen-ai-usage-attributes-as-non-authoritative-when-a-tool-call-event-stream-is-truncated-m.warrant.json
# Markdown SHA-256:   6b411c48282f3b6d32f78e1f48ac290b4f11de346b837dc751addebbb4d80e95
# Code AST SHA-256:   843fd051e673109abb9d84c5e6edce56ef78d683ebcaced19bc6bf25a5c22f84
# Verified Classes:   UsageEventStreamMismatch, AgentSpanRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UsageEventStreamMismatch(RuntimeError):
    """Raised when gen_ai.usage.* cannot be safely paired with the tool-call event stream."""
    pass


@dataclass
class AgentSpanRecord:
    close_reason: str                 # "completed" | "budget_exhausted" | "deadline" | "error"
    input_tokens: int
    output_tokens: int
    tool_call_starts: int
    tool_call_ends: int
    orphan_start_ids: frozenset      # starts with no matching end
    dropped_events: int
    last_event_offset_ms: int         # span_end - last_event_ts
    flush_interval_ms: int


def derive_cost_per_tool_call(span: AgentSpanRecord) -> Optional[float]:
    # Refuse per-call derivation unless the event stream is provably complete.
    if span.close_reason != "completed":
        raise UsageEventStreamMismatch(
            f"span closed via {span.close_reason!r}; usage totals valid, "
            f"event stream not a valid denominator"
        )
    if span.tool_call_starts != span.tool_call_ends:
        raise UsageEventStreamMismatch(
            f"unbalanced tool-call events: {span.tool_call_starts} starts, "
            f"{span.tool_call_ends} ends"
        )
    if span.orphan_start_ids:
        raise UsageEventStreamMismatch(
            f"orphaned tool-call starts: {sorted(span.orphan_start_ids)}"
        )
    if span.dropped_events > 0:
        raise UsageEventStreamMismatch(
            f"exporter dropped {span.dropped_events} events; denominator unreliable"
        )
    if span.last_event_offset_ms < span.flush_interval_ms:
        raise UsageEventStreamMismatch(
            f"last event within {span.last_event_offset_ms}ms of span end; "
            f"possible add_event/end() race"
        )
    if span.tool_call_ends == 0:
        return None  # no tool calls; per-call metric undefined, not an error
    total = span.input_tokens + span.output_tokens
    return total / span.tool_call_ends
