# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-the-tool-call-token-accounting-reconciliation-invariant-and-its-silent-violati.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-the-tool-call-token-accounting-reconciliation-invariant-and-its-silent-violati.warrant.json
# Markdown SHA-256:   2126102af5ae0089a33e2b4789870a534bf60a5db808af67813cf25765bb4cf3
# Code AST SHA-256:   d4d146522dc8cee7472e887aadbace76fcadc7590d8262fa05982280774c381c
# Verified Classes:   SpanSealViolation, ToolCallState, GenAISpanState
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field


class SpanSealViolation(RuntimeError):
    """Raised when a GenAI span is closed before its tool-call and usage
    attributes reach a jointly consistent state."""
    pass


@dataclass
class ToolCallState:
    call_id: str
    arguments_buffer: str = ""
    sealed: bool = False

    def arguments(self) -> dict:
        if not self.sealed:
            raise SpanSealViolation(
                f"tool call {self.call_id!r} arguments read before terminal delta"
            )
        try:
            return json.loads(self.arguments_buffer)
        except json.JSONDecodeError as exc:
            raise SpanSealViolation(
                f"tool call {self.call_id!r} arguments not valid JSON at seal: {exc}"
            ) from exc


@dataclass
class GenAISpanState:
    operation: str
    tool_calls: dict[str, ToolCallState] = field(default_factory=dict)
    usage_sealed: bool = False
    output_tokens: int = 0
    retry_lineage: str | None = None

    def record_delta(self, call_id: str, delta: str, terminal: bool) -> None:
        state = self.tool_calls.setdefault(call_id, ToolCallState(call_id))
        if state.sealed:
            raise SpanSealViolation(
                f"delta for already-sealed tool call {call_id!r}"
            )
        state.arguments_buffer += delta
        if terminal:
            state.sealed = True

    def record_usage(self, output_tokens: int, final: bool) -> None:
        if self.usage_sealed:
            raise SpanSealViolation("usage recorded after seal")
        self.output_tokens = output_tokens
        if final:
            self.usage_sealed = True

    def close(self) -> dict:
        unsealed = [c for c in self.tool_calls.values() if not c.sealed]
        if unsealed:
            raise SpanSealViolation(
                f"refusing to close span: {len(unsealed)} tool call(s) "
                f"unsealed: {[c.call_id for c in unsealed]}"
            )
        if not self.usage_sealed:
            raise SpanSealViolation(
                "refusing to close span: usage chunk not marked final"
            )
        # Materialize arguments only now, when every call is sealed.
        return {
            "gen_ai.operation.name": self.operation,
            "gen_ai.usage.output_tokens": self.output_tokens,
            "gen_ai.tool.call.count": len(self.tool_calls),
            "gen_ai.tool.call.arguments": {
                cid: c.arguments() for cid, c in self.tool_calls.items()
            },
        }


def close_turn(spans: list[GenAISpanState]) -> dict:
    """Close a logical turn, deduplicating retry lineage at the parent."""
    by_lineage: dict[str, int] = {}
    for span in spans:
        if span.retry_lineage is None:
            continue
        if span.retry_lineage in by_lineage:
            raise SpanSealViolation(
                f"duplicate retry lineage {span.retry_lineage!r} across spans; "
                "retry must be modeled as a child span, not a sibling"
            )
        by_lineage[span.retry_lineage] = span.output_tokens
    return {"spans": [s.close() for s in spans]}
