# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-token-accounting-divergence-when-a-genai-agent-span-s-genai-usage-output-tokens-is-emitted-before-the-model-s-strea.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-token-accounting-divergence-when-a-genai-agent-span-s-genai-usage-output-tokens-is-emitted-before-the-model-s-strea.warrant.json
# Markdown SHA-256:   67c206fa34ffa293df087e9fe5053b0d7ec7e1dbe3bd4668405c774382bb1874
# Code AST SHA-256:   96ba80213de82a0701fda14a71191fb78905596396f26d2c19c167b90faab605
# Verified Classes:   TokenAccountingClosureError, ToolCallAccumulator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field


class TokenAccountingClosureError(RuntimeError):
    """Raised when a GenAI span would close with usage reported but
    tool-call arguments unsealed or unparseable."""


@dataclass
class ToolCallAccumulator:
    args_by_index: dict = field(default_factory=dict)
    sealed_indexes: set = field(default_factory=set)
    sealed_at_seq: int = -1
    seq: int = 0

    def ingest_delta(self, index: int, fragment: str) -> None:
        self.seq += 1
        self.args_by_index[index] = self.args_by_index.get(index, "") + fragment

    def seal(self, index: int) -> None:
        self.seq += 1
        self.sealed_indexes.add(index)
        self.sealed_at_seq = self.seq

    def is_complete(self, index: int) -> bool:
        if index not in self.sealed_indexes:
            return False
        try:
            json.loads(self.args_by_index.get(index, ""))
            return True
        except json.JSONDecodeError:
            return False


def close_genai_span(span, acc: ToolCallAccumulator, output_tokens: int,
                     usage_seq: int, grace_expired: bool) -> None:
    """Enforce token-accounting closure before ending the span."""
    open_indexes = [i for i in acc.args_by_index if not acc.is_complete(i)]

    if open_indexes and not grace_expired:
        # Do not close; wait for the bounded grace window to seal arguments.
        raise TokenAccountingClosureError(
            f"refusing to close span: tool-call indexes {open_indexes} "
            f"unsealed after usage_seq={usage_seq}"
        )

    if open_indexes and grace_expired:
        # Explicit falsification: export partial payload, flag it.
        span.set_attribute("genai.tool.call.arguments.truncated", True)
        span.set_attribute("genai.tool.call.arguments.unsealed_indexes",
                           ",".join(map(str, open_indexes)))
        span.set_attribute("genai.usage.output_tokens", output_tokens)
        span.end()
        return

    if usage_seq < acc.sealed_at_seq:
        raise TokenAccountingClosureError(
            f"usage_seq={usage_seq} predates sealed_at_seq={acc.sealed_at_seq}; "
            f"token count cannot describe sealed arguments"
        )

    for index, payload in acc.args_by_index.items():
        span.set_attribute(f"genai.tool.call.arguments[{index}]", payload)
    span.set_attribute("genai.usage.output_tokens", output_tokens)
    span.end()
