# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-per-turn-cost-attribution-silently-drift-when-a-multi-turn-trajectory-is-replayed-from-a-mid-conversation-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-per-turn-cost-attribution-silently-drift-when-a-multi-turn-trajectory-is-replayed-from-a-mid-conversation-checkpoint.warrant.json
# Markdown SHA-256:   385bff1e24f73b534714d1ea667d1509dbf25bad8cd98d71fdf9e18ddc00a48e
# Code AST SHA-256:   374a1059668f1a76699d24868a1e9c0033eee2982239bf516ce2172e9678fd96
# Verified Classes:   TrajectoryAttributionDrift
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TrajectoryAttributionDrift(RuntimeError):
    """Raised when a resumed turn's reconstructed context does not match its billed usage."""


def attribute_turn_cost(
    turn_index: int,
    reconstructed_prompt_tokens: int,
    billed_prompt_tokens: int,
    billed_completion_tokens: int,
    tokenizer_version_generation: str,
    tokenizer_version_replay: str,
    is_resumed: bool,
) -> dict:
    """
    Attribute cost to a single turn. Refuses to smooth across a reconstruction boundary.
    Returns a ledger entry, or raises if reconstruction fidelity cannot be established.
    """
    if tokenizer_version_generation != tokenizer_version_replay:
        raise TrajectoryAttributionDrift(
            f"turn {turn_index}: tokenizer version mismatch "
            f"({tokenizer_version_generation!r} vs {tokenizer_version_replay!r}); "
            f"reconstructed token counts are not comparable to billed counts"
        )

    if is_resumed and reconstructed_prompt_tokens != billed_prompt_tokens:
        delta = billed_prompt_tokens - reconstructed_prompt_tokens
        raise TrajectoryAttributionDrift(
            f"turn {turn_index}: reconstruction infidelity on resume — "
            f"reconstructed={reconstructed_prompt_tokens}, billed={billed_prompt_tokens}, "
            f"delta={delta}. Refusing to attribute or smooth. Mark turn unreconciled."
        )

    return {
        "turn_index": turn_index,
        "prompt_tokens": billed_prompt_tokens,
        "completion_tokens": billed_completion_tokens,
        "reconciled": True,
        "smoothed": False,
    }


def build_trajectory_ledger(turns: list[dict]) -> list[dict]:
    """
    Build a per-turn ledger. Any turn that fails fidelity is recorded as unreconciled
    and excluded from per-turn cost analysis, but the trajectory total is still preserved
    from the billed usage fields.
    """
    ledger = []
    for t in turns:
        try:
            entry = attribute_turn_cost(**t)
        except TrajectoryAttributionDrift as exc:
            entry = {
                "turn_index": t["turn_index"],
                "prompt_tokens": t["billed_prompt_tokens"],
                "completion_tokens": t["billed_completion_tokens"],
                "reconciled": False,
                "smoothed": False,
                "reason": str(exc),
            }
        ledger.append(entry)
    return ledger
