# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-emit-a-valid-gen-ai-operation-name-span-with-gen-ai-usage-attributes-that-silently-under-bill-a-retried-tool-call-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-emit-a-valid-gen-ai-operation-name-span-with-gen-ai-usage-attributes-that-silently-under-bill-a-retried-tool-call-fan-out.warrant.json
# Markdown SHA-256:   de35e426005b23570be72f93f687b9d78d1fd65b3dd4e8bc5bfb207c6443ea4a
# Code AST SHA-256:   91cf0a0a7586b4335ba24e5efb90b40ae110d134843b298f3e513e7a37768172
# Verified Classes:   CostRollupInvariantError, GenAiSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CostRollupInvariantError(RuntimeError):
    """Raised when a span set cannot be rolled up to a defensible cost figure."""


@dataclass
class GenAiSpan:
    span_id: str
    operation_name: str                      # gen_ai.operation.name
    status_code: str                         # "OK" | "ERROR"
    input_tokens: Optional[int] = None       # gen_ai.usage.input_tokens
    output_tokens: Optional[int] = None      # gen_ai.usage.output_tokens
    usage_source: Optional[str] = None       # "estimated" | "reported" | None
    agent_step_id: Optional[str] = None      # runtime-minted, NOT in the convention
    attempt_ordinal: Optional[int] = None    # runtime-minted, NOT in the convention


def rollup_step_cost(spans: list[GenAiSpan]) -> dict[str, tuple[int, int]]:
    """
    Group chat spans by agent.step.id and select the billed attempt per step.
    Refuses to sum across attempts, and refuses estimated-usage spans as billable.
    """
    chat_spans = [s for s in spans if s.operation_name == "chat"]
    if not chat_spans:
        return {}

    # Invariant 1: every cost-bearing span must declare usage provenance.
    unprovenanced = [s for s in chat_spans if s.usage_source is None]
    if unprovenanced:
        raise CostRollupInvariantError(
            f"{len(unprovenanced)} chat span(s) lack gen_ai.usage.source; "
            "cannot distinguish estimated from reported usage. "
            f"span_ids={[s.span_id for s in unprovenanced]}"
        )

    # Invariant 2: within a step, attempts must be ordered; otherwise dedup is undefined.
    by_step: dict[str, list[GenAiSpan]] = {}
    for s in chat_spans:
        key = s.agent_step_id or f"__unkeyed__:{s.span_id}"
        by_step.setdefault(key, []).append(s)

    result: dict[str, tuple[int, int]] = {}
    for step_id, attempts in by_step.items():
        if len(attempts) > 1 and any(a.attempt_ordinal is None for a in attempts):
            raise CostRollupInvariantError(
                f"step {step_id!r} has {len(attempts)} attempts but at least one "
                "lacks agent.attempt.ordinal; retry dedup is undefined. "
                "Summing would double-count."
            )
        billed = [a for a in attempts if a.usage_source == "reported"]
        if not billed:
            # All attempts were estimated (e.g., every attempt errored pre-response).
            # Zero billable usage is the defensible answer; do not guess.
            result[step_id] = (0, 0)
            continue
        chosen = max(billed, key=lambda a: a.attempt_ordinal or 0)
        result[step_id] = (chosen.input_tokens or 0, chosen.output_tokens or 0)
    return result


def reconcile_against_invoice(rolled: dict[str, tuple[int, int]], invoice_in: int) -> None:
    total_in = sum(v[0] for v in rolled.values())
    if total_in != invoice_in:
        raise CostRollupInvariantError(
            f"span-derived input tokens ({total_in}) disagree with provider invoice "
            f"({invoice_in}); likely a retry path billed by the provider but not "
            "tagged with agent.attempt.ordinal, or a fan-out step missing agent.step.id."
        )
