# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-token-accounting-spans-when-a-genai-tool-call-span-is-emitted-twice-under-retry-once-by-the-client-and-once-by-the-se.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-token-accounting-spans-when-a-genai-tool-call-span-is-emitted-twice-under-retry-once-by-the-client-and-once-by-the-se.warrant.json
# Markdown SHA-256:   093a024f04308c04b55437e7e3177caca73857050551fc00ae6864c9c6140d50
# Code AST SHA-256:   51458cfc64ca78452d02817247319c80bef4f0d846999cd9c80609ae87af8d5f
# Verified Classes:   TokenReconciliationError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class TokenReconciliationError(RuntimeError):
    """Raised when a trace's GenAI spans cannot be safely reconciled."""


@dataclass(frozen=True)
class GenAISpan:
    trace_id: str
    span_id: str
    emitter: str          # "client" | "server"
    call_id: str          # gen_ai.tool.call.id
    original_call_id: str | None  # app.retry.original_call_id
    output_tokens: int
    status: str           # "OK" | "ERROR" | "UNSET"
    error_type: str | None


def reconcile_output_tokens(spans: Iterable[GenAISpan]) -> int:
    spans = list(spans)
    if not spans:
        return 0

    traces = {s.trace_id for s in spans}
    if len(traces) != 1:
        raise TokenReconciliationError(
            f"spans span multiple traces {traces}; retry propagation broken"
        )

    # Group by logical call. Every span must carry the grouping key.
    groups: dict[str, list[GenAISpan]] = {}
    for s in spans:
        if s.original_call_id is None:
            raise TokenReconciliationError(
                f"span {s.span_id} (emitter={s.emitter}, call_id={s.call_id}) "
                f"missing app.retry.original_call_id; cannot attribute tokens"
            )
        groups.setdefault(s.original_call_id, []).append(s)

    total = 0
    for logical_id, group in groups.items():
        # Per distinct attempt (call_id), take the max across client/server
        # emitters. Sum across distinct attempts.
        by_attempt: dict[str, list[GenAISpan]] = {}
        for s in group:
            by_attempt.setdefault(s.call_id, []).append(s)

        for attempt_id, attempt_spans in by_attempt.items():
            server_spans = [s for s in attempt_spans if s.emitter == "server"]
            if not server_spans:
                # Client-only attempt: the server never reported generated
                # tokens. Treat client count as a lower bound and flag.
                client_max = max(s.output_tokens for s in attempt_spans)
                total += client_max
                continue
            server_max = max(s.output_tokens for s in server_spans)
            # If the server reported a client_disconnect error, its count is a
            # lower bound on generation; accept it but do not add client count.
            if any(
                s.error_type == "client_disconnect" for s in server_spans
            ):
                total += server_max
                continue
            total += server_max

    return total


def attribute_call(spans: list[GenAISpan]) -> dict[str, int]:
    """Return billable token attribution for a logical tool call."""
    if not spans:
        raise TokenReconciliationError("no spans supplied for attribution")
    try:
        return {"billable_output_tokens": reconcile_output_tokens(spans)}
    except TokenReconciliationError as exc:
        raise TokenReconciliationError(
            f"refusing to attribute tokens for trace "
            f"{spans[0].trace_id}: {exc}"
        ) from exc
