# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-closure-before-cost-telemetry-can-be-trusted-in-agent-runs.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-closure-before-cost-telemetry-can-be-trusted-in-agent-runs.warrant.json
# Markdown SHA-256:   fd834b40f750ceb69272e25c01fac470663406ca2e6cdc989c21d40afa9263bb
# Code AST SHA-256:   a8e521b92a9e604190858d2c64b04f9b08c1999165e93b1599fc9a9d9fe3b49c
# Verified Classes:   CostSealViolation, SpanUsage, AgentSpanAccumulator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class CostSealViolation(RuntimeError):
    """Raised when a parent agent span attempts to seal cost before all
    descendant chat spans have ended and usage has been accumulated by span_id."""


@dataclass
class SpanUsage:
    span_id: str
    operation: str
    input_tokens: int
    output_tokens: int
    ended: bool = False


@dataclass
class AgentSpanAccumulator:
    parent_id: str
    price_per_token: float = 1e-6
    _usage: dict[str, SpanUsage] = field(default_factory=dict)
    _open_chat: set[str] = field(default_factory=set)
    _open_tools: set[str] = field(default_factory=set)

    def register_chat(self, span_id: str) -> None:
        self._open_chat.add(span_id)

    def register_tool(self, span_id: str) -> None:
        self._open_tools.add(span_id)

    def record_usage(self, span_id: str, op: str, inp: int, out: int) -> None:
        # keyed by span_id, so retries are additive, never overwriting
        existing = self._usage.get(span_id)
        if existing is not None:
            existing.input_tokens += inp
            existing.output_tokens += out
        else:
            self._usage[span_id] = SpanUsage(span_id, op, inp, out)

    def end_span(self, span_id: str) -> None:
        self._open_chat.discard(span_id)
        self._open_tools.discard(span_id)
        if span_id in self._usage:
            self._usage[span_id].ended = True

    def seal_cost(self) -> float:
        # invariant: no open chat or tool descendants, and every chat span
        # that ever registered is present in the usage map and ended.
        if self._open_chat or self._open_tools:
            raise CostSealViolation(
                f"parent {self.parent_id} cannot seal cost: "
                f"{len(self._open_chat)} open chat spans, "
                f"{len(self._open_tools)} open tool spans"
            )
        for span_id, u in self._usage.items():
            if not u.ended:
                raise CostSealViolation(
                    f"parent {self.parent_id}: usage for {span_id} "
                    f"recorded but span not ended; cost would be unsealed"
                )
        total = sum(u.input_tokens + u.output_tokens for u in self._usage.values())
        return total * self.price_per_token


def end_agent_run(acc: AgentSpanAccumulator, flush_barrier: callable) -> float:
    # force_flush must complete before seal is trusted by consumers
    flush_barrier()
    try:
        return acc.seal_cost()
    except CostSealViolation as e:
        # do NOT write a partial cost_usd; degrade to estimate flag instead
        raise CostSealViolation(f"refusing to emit cost_usd for {acc.parent_id}: {e}")
