# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-genai-token-attributes-when-a-streaming-tool-call-span-closes-before-its-usage-chunk-arrives.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-genai-token-attributes-when-a-streaming-tool-call-span-closes-before-its-usage-chunk-arrives.warrant.json
# Markdown SHA-256:   7b7162f40b777c1a894e1a4e5fb5fbee0fbfe21e37e1c79deffaad551b2311ac
# Code AST SHA-256:   ff6d0f16bc837add3052550806fef03b11fcb53661d6c39efafccf32b3fe6fe0
# Verified Classes:   UsageFinalizationError, InvocationSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class UsageFinalizationError(RuntimeError):
    """Raised when an invocation span is finalized before usage telemetry is resolved."""


@dataclass
class InvocationSpan:
    span_id: str
    gen_ai_usage_output_tokens: Optional[int] = None
    finalized: bool = False
    events: list = field(default_factory=list)

    def finalize(self) -> None:
        if self.finalized:
            raise UsageFinalizationError(f"span {self.span_id} finalized twice")
        self.finalized = True


def close_invocation_span(
    span: InvocationSpan,
    finish_reason_seen: bool,
    stream_drained: bool,
    drain_deadline_s: float,
    now: float,
) -> None:
    """
    Enforce the invariant: do not finalize an invocation span while
    finish_reason is seen, usage is unset, and the stream is still open.
    """
    usage_missing = span.gen_ai_usage_output_tokens is None

    if finish_reason_seen and usage_missing and not stream_drained:
        remaining = drain_deadline_s - now
        if remaining > 0:
            # Keep span open; caller must continue draining for usage chunk.
            raise UsageFinalizationError(
                f"span {span.span_id}: finish_reason observed but usage chunk "
                f"not yet received; {remaining:.3f}s of drain budget remain. "
                "Refusing to finalize — would emit zero-cost tool activity."
            )
        # Deadline expired: finalize but mark usage as explicitly unknown.
        span.events.append(
            {"name": "gen_ai.usage.drain_timeout", "attrs": {"drain_deadline_s": drain_deadline_s}}
        )

    span.finalize()


def handle_stream_end(
    span: InvocationSpan,
    finish_reason_seen: bool,
    usage_chunk_received: bool,
    stream_drained: bool,
    drain_deadline_s: float,
) -> None:
    if usage_chunk_received and span.gen_ai_usage_output_tokens is None:
        raise UsageFinalizationError(
            f"span {span.span_id}: usage chunk flagged received but attribute unset — "
            "accumulator reset by finish_reason handler."
        )
    close_invocation_span(
        span=span,
        finish_reason_seen=finish_reason_seen,
        stream_drained=stream_drained,
        drain_deadline_s=drain_deadline_s,
        now=time.monotonic(),
    )
