# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-span-attributes-against-the-tokenizer-s-own-accounting-before-trusting-a-tool-call-sp.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-span-attributes-against-the-tokenizer-s-own-accounting-before-trusting-a-tool-call-sp.warrant.json
# Markdown SHA-256:   2c7ec148a400b16aab2ffde674869b9f0cda07214ecad597228f200326397ba3
# Code AST SHA-256:   c53b1485a49d6f698299bb1ca093f6e95183757a218e20712bf952793b0ff2b2
# Verified Classes:   LedgerCorruptionError, GenAISpan, BudgetLedger, Tokenizer
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class LedgerCorruptionError(RuntimeError):
    """Raised when span-reported usage diverges from local tokenization beyond tolerance."""
    pass


@dataclass
class GenAISpan:
    step: int
    operation: str                      # "chat" | "execute_tool"
    reported_input_tokens: Optional[int]  # gen_ai.usage.input_tokens, may be None
    declared_tool_count: int
    assembled_prompt: str
    reconciled: bool = False


@dataclass
class BudgetLedger:
    local_tokenizer: "Tokenizer"
    scaffolding_budget: int = 2_000     # cumulative tolerance for schema/preamble drift
    per_step_tolerance: int = 40
    cumulative_local: int = 0
    cumulative_reported: int = 0
    steps: list = field(default_factory=list)

    def admit(self, span: GenAISpan) -> None:
        local_count = self.local_tokenizer.count(span.assembled_prompt)
        # Estimate provider-side scaffolding the span cannot see.
        scaffolding = self._estimate_scaffolding(span.declared_tool_count)
        local_count += scaffolding

        if span.reported_input_tokens is None:
            # Absent usage: valid span, non-ledger-grade. Local count wins.
            span.reconciled = False
            self.cumulative_local += local_count
            self.steps.append(span)
            return

        drift = abs(local_count - span.reported_input_tokens)
        if drift > self.per_step_tolerance and span.declared_tool_count == 0:
            # Unexplained drift on a no-tool turn: tokenizer mismatch.
            raise LedgerCorruptionError(
                f"step {span.step}: per-step drift {drift} exceeds "
                f"{self.per_step_tolerance} with no tool scaffolding to explain it"
            )

        span.reconciled = True
        self.cumulative_local += local_count
        self.cumulative_reported += span.reported_input_tokens
        self.steps.append(span)

        cumulative_gap = self.cumulative_local - self.cumulative_reported
        if cumulative_gap > self.scaffolding_budget:
            raise LedgerCorruptionError(
                f"step {span.step}: cumulative ledger divergence {cumulative_gap} "
                f"exceeds scaffolding budget {self.scaffolding_budget}; "
                f"checkpoint-and-distill required before continuing"
            )

    @staticmethod
    def _estimate_scaffolding(declared_tool_count: int) -> int:
        # Empirically ~150 tokens of JSON schema per declared tool.
        return declared_tool_count * 150


class Tokenizer:
    def count(self, text: str) -> int:
        # Placeholder: real impl uses the provider's tokenizer family/version.
        return len(text.split())
