# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reconcile-opentelemetry-genai-semantic-convention-spans-against-its-own-loop-counter-before-exporting-cost-attribution.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reconcile-opentelemetry-genai-semantic-convention-spans-against-its-own-loop-counter-before-exporting-cost-attribution.warrant.json
# Markdown SHA-256:   7927a3b4ada5458789e7921b7acc38ea7602d9325d9b495e7d906dec15ce6754
# Code AST SHA-256:   a5874bfe1740d722421954ad9bd53bdcd59ac77db790f0784efb950ee9a8895d
# Verified Classes:   CostAttributionInvariantError, LoopCounter, SpanLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CostAttributionInvariantError(RuntimeError):
    """Raised when the span ledger cannot be reconciled to the loop counter."""
    pass


@dataclass
class LoopCounter:
    llm_calls: int = 0          # logical calls, incremented once per call
    tool_calls: int = 0


@dataclass
class SpanLedger:
    ended_chat_spans: int = 0
    input_tokens: int = 0
    output_tokens: int = 0
    usage_missing: int = 0
    sampling_ratio: float | None = None  # None => unsampled / unknown


def reconcile_and_attribute(
    counter: LoopCounter,
    ledger: SpanLedger,
    in_flight_at_shutdown: int = 0,
    dropped_on_shutdown: int = 0,
) -> dict:
    """
    Enforce ledger == loop_counter (or explained delta) before publishing cost.
    Returns a dict with either an exact total or an explicit lower bound + delta.
    """
    explained_delta = in_flight_at_shutdown + dropped_on_shutdown
    observed = ledger.ended_chat_spans
    expected = counter.llm_calls

    unexplained = expected - observed - explained_delta

    if unexplained < 0:
        # More spans than logical calls => retry shadowing or double-emit.
        raise CostAttributionInvariantError(
            f"ledger over-counts: {observed} ended spans vs "
            f"{expected} logical calls (explained={explained_delta}); "
            "retries must be child spans or counter must count attempts"
        )

    if unexplained > 0:
        # Spans missing with no explanation => do NOT publish an exact total.
        raise CostAttributionInvariantError(
            f"ledger under-counts by {unexplained} call(s) with no recorded "
            "cause (in_flight/dropped); refusing to publish exact cost"
        )

    if ledger.usage_missing > 0:
        raise CostAttributionInvariantError(
            f"{ledger.usage_missing} ended span(s) lack gen_ai.usage.*; "
            "cost total would be a lower bound"
        )

    raw_tokens = ledger.input_tokens + ledger.output_tokens
    if ledger.sampling_ratio is not None and ledger.sampling_ratio <= 0:
        raise CostAttributionInvariantError(
            f"invalid sampling_ratio={ledger.sampling_ratio}; cannot un-scale"
        )

    scale = 1.0 if ledger.sampling_ratio is None else 1.0 / ledger.sampling_ratio
    return {
        "exact": True,
        "chat_spans": observed,
        "logical_calls": expected,
        "explained_delta": explained_delta,
        "tokens_scaled": int(raw_tokens * scale),
        "sampling_ratio": ledger.sampling_ratio,
        "provenance": "reconciled",
    }
