# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-parent-child-span-link-when-the-parent-s-gen-ai-usage-input-tokens-reflects-a-cached-token-breakdown-t.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-parent-child-span-link-when-the-parent-s-gen-ai-usage-input-tokens-reflects-a-cached-token-breakdown-t.warrant.json
# Markdown SHA-256:   4f76fc87d5d2ab82a9d168e618bb6315c3d7c79b553088d51003099ccc7139ed
# Code AST SHA-256:   4ed1737524df4bc5855bc67f90ec37f0edf83473a0c15a4eade19e52ea396724
# Verified Classes:   CacheAttributionViolation, TokenDecomp, SpanEmission
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CacheAttributionViolation(RuntimeError):
    """Raised when a child span's cache accounting cannot be reconciled with its parent."""


@dataclass(frozen=True)
class TokenDecomp:
    input_tokens: int
    cache_read_input_tokens: int
    cache_creation_input_tokens: int = 0


@dataclass(frozen=True)
class SpanEmission:
    span_kind: str        # "INTERNAL" (child) or "CLIENT" (link)
    parent_span_id: Optional[str]
    tokens: TokenDecomp
    cache_attribution: str  # "resolved" | "unresolved"


def decide_child_emission(
    parent: TokenDecomp,
    parent_span_id: str,
    child: TokenDecomp,
    parent_decomp_in_baggage: bool,
    prefix_preserved: bool,
    cache_epoch_changed: bool,
) -> SpanEmission:
    # Hard invariant: a child can never claim more cache reads than the parent saw.
    if child.cache_read_input_tokens > parent.cache_read_input_tokens:
        raise CacheAttributionViolation(
            f"child cache_read={child.cache_read_input_tokens} exceeds "
            f"parent cache_read={parent.cache_read_input_tokens}; "
            f"epoch_changed={cache_epoch_changed}, baggage={parent_decomp_in_baggage}"
        )

    resolved = (
        parent_decomp_in_baggage
        and prefix_preserved
        and not cache_epoch_changed
    )

    if resolved:
        return SpanEmission(
            span_kind="INTERNAL",
            parent_span_id=parent_span_id,
            tokens=child,
            cache_attribution="resolved",
        )

    # Downgrade to peer link; child tokens are informational only.
    return SpanEmission(
        span_kind="CLIENT",
        parent_span_id=None,
        tokens=child,
        cache_attribution="unresolved",
    )


def reconcile(parent: TokenDecomp, children: list[SpanEmission]) -> None:
    attributed = [c for c in children if c.cache_attribution == "resolved"]
    sum_input = sum(c.tokens.input_tokens for c in attributed)
    sum_cache = sum(c.tokens.cache_read_input_tokens for c in attributed)

    if sum_input > parent.input_tokens:
        raise CacheAttributionViolation(
            f"resolved children input sum {sum_input} > parent {parent.input_tokens}"
        )
    if sum_cache > parent.cache_read_input_tokens:
        raise CacheAttributionViolation(
            f"resolved children cache sum {sum_cache} > parent {parent.cache_read_input_tokens}"
        )
