# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-gen-ai-usage-token-counts-when-a-streamed-tool-call-span-closes-before-the-provider-s-final-usage.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-gen-ai-usage-token-counts-when-a-streamed-tool-call-span-closes-before-the-provider-s-final-usage.warrant.json
# Markdown SHA-256:   8a0845eef0843c979353898e330baf5875faeb6abe1e2a5861306fb5aec04304
# Code AST SHA-256:   ee8562e5d3b798ec322fc3bbd36c98c1b298925a925252c8533cd2150bacd5a6
# Verified Classes:   UsageAccountingViolation, ChatSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UsageAccountingViolation(RuntimeError):
    """Raised when a gen_ai.chat span would close without valid usage accounting."""


USAGE_DELIVERY_TERMINAL_FRAME = "terminal_frame"
USAGE_DELIVERY_MESSAGE_BODY = "message_body"


class ChatSpan:
    def __init__(self, provider_usage_delivery: str, deadline_s: float = 5.0):
        self.provider_usage_delivery = provider_usage_delivery
        self.deadline_s = deadline_s
        self.usage = None            # dict once terminal frame consumed
        self.content_complete = False
        self.frame_lost = False

    def attach_usage(self, input_tokens: int, output_tokens: int) -> None:
        self.usage = {
            "gen_ai.usage.input_tokens": input_tokens,
            "gen_ai.usage.output_tokens": output_tokens,
        }

    def mark_frame_lost(self) -> None:
        self.frame_lost = True

    def end(self) -> dict:
        # Invariant: never emit fabricated or stale counts as canonical usage.
        if self.provider_usage_delivery == USAGE_DELIVERY_TERMINAL_FRAME:
            if self.usage is None and not self.frame_lost:
                # Content finished but the accounting frame has not been consumed
                # and no deadline has fired: closing now would silently drop usage.
                raise UsageAccountingViolation(
                    "terminal-frame provider: span ended before usage frame consumed; "
                    "hold open until frame arrives or deadline marks frame_lost"
                )
            if self.usage is None and self.frame_lost:
                # Explicit absence, never backfilled from a local tokenizer.
                return {"agent.usage.missing_reason": "terminal_frame_lost"}
        if self.provider_usage_delivery == USAGE_DELIVERY_MESSAGE_BODY:
            if self.usage is None:
                raise UsageAccountingViolation(
                    "message-body provider: usage must be attached at assembly time"
                )
        return dict(self.usage)


def close_chat_span(span: ChatSpan, elapsed_since_last_byte: float) -> dict:
    if elapsed_since_last_byte > span.deadline_s and span.usage is None:
        span.mark_frame_lost()
    return span.end()
