# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-the-genai-span-s-gen-ai-usage-token-counters-when-a-streaming-tool-call-loop-emits-partial-deltas-before-the-model-s-fini.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-the-genai-span-s-gen-ai-usage-token-counters-when-a-streaming-tool-call-loop-emits-partial-deltas-before-the-model-s-fini.warrant.json
# Markdown SHA-256:   6a09a3fe2927cc751738bd3d58336d1a1f60a023e825ae2b89ee6abe9943f32e
# Code AST SHA-256:   012d450bb20a8466f5744822fa1ce0dbe2c16136faf4008d22554a7e1899bdeb
# Verified Classes:   GenAIUsageFinalizationError, StreamState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class GenAIUsageFinalizationError(RuntimeError):
    """Raised when a GenAI span cannot settle gen_ai.usage.* truthfully."""


@dataclass
class StreamState:
    finish_reason: Optional[str] = None
    usage_chunk_seen: bool = False
    prompt_tokens: Optional[int] = None
    completion_tokens: Optional[int] = None
    saw_delta_usage: bool = False  # provider emitted per-chunk usage


TERMINAL_REASONS = {"stop", "length", "content_filter"}
TOOL_BOUNDARY_REASONS = {"tool_calls", "function_call"}


def finalize_genai_usage(state: StreamState, *, allow_unknown: bool) -> Optional[tuple[int, int]]:
    """
    Returns (input_tokens, output_tokens) to write ONCE onto the span, or None
    if usage is legitimately unknown (attribute must be omitted, not zeroed).

    Raises GenAIUsageFinalizationError when the state cannot be settled
    truthfully and allow_unknown is False (strict mode).
    """
    if state.finish_reason is None:
        raise GenAIUsageFinalizationError(
            "stream ended without finish_reason; usage cannot be settled"
        )

    if state.finish_reason in TOOL_BOUNDARY_REASONS:
        # Tool-call boundary is NOT a completion boundary.
        if state.usage_chunk_seen and state.prompt_tokens is not None:
            return (state.prompt_tokens, state.completion_tokens or 0)
        if allow_unknown:
            return None  # omit attribute; never write (0, 0)
        raise GenAIUsageFinalizationError(
            "tool_calls finish with no usage chunk; refusing to write 0/0"
        )

    if state.finish_reason in TERMINAL_REASONS:
        if state.usage_chunk_seen and state.prompt_tokens is not None:
            return (state.prompt_tokens, state.completion_tokens or 0)
        if allow_unknown:
            return None
        raise GenAIUsageFinalizationError(
            "terminal finish but usage chunk never arrived"
        )

    raise GenAIUsageFinalizationError(
        f"unhandled finish_reason={state.finish_reason!r}"
    )
