# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-divergence-between-its-recorded-trajectory-and-a-replayed-counterfactual-when-tool-outputs-are-non-deterministic-and-the-r.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-divergence-between-its-recorded-trajectory-and-a-replayed-counterfactual-when-tool-outputs-are-non-deterministic-and-the-r.warrant.json
# Markdown SHA-256:   1ad23f80f41faf546e25725f6be702f817067f9b8419eb5d20e7e866ed1d5774
# Code AST SHA-256:   c77f3519cf0d6342242ba398b43a7e31d88fa949307974838ee925fe6834b77b
# Verified Classes:   ReplayMode, ObservationProvenance, ReplayDivergenceError, Observation, RecordedStep
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class ReplayMode(str, Enum):
    OBSERVATIONAL = "observational"
    CAUSAL = "causal"


class ObservationProvenance(str, Enum):
    RECORDED = "recorded"
    LIVE = "live"
    FUZZY = "fuzzy"


class ReplayDivergenceError(RuntimeError):
    """Raised when a counterfactual replay serves an observation that does not
    hash-match the recorded trajectory before the declared perturbation index."""


@dataclass(frozen=True)
class Observation:
    step_index: int
    tool_name: str
    args_canonical: str
    payload: bytes
    provenance: ObservationProvenance
    matched_record_hash: str | None

    def payload_hash(self) -> str:
        return hashlib.sha256(self.payload).hexdigest()


@dataclass(frozen=True)
class RecordedStep:
    step_index: int
    tool_name: str
    args_canonical: str
    observation_hash: str


def enforce_observational_prefix(
    replay: list[Observation],
    record: list[RecordedStep],
    perturbation_index: int,
    mode: ReplayMode,
) -> None:
    if mode is not ReplayMode.OBSERVATIONAL:
        return

    record_by_index = {r.step_index: r for r in record}

    for obs in replay:
        if obs.step_index >= perturbation_index:
            break

        recorded = record_by_index.get(obs.step_index)
        if recorded is None:
            raise ReplayDivergenceError(
                f"step {obs.step_index}: no recorded step to validate against"
            )

        if obs.provenance is not ObservationProvenance.RECORDED:
            raise ReplayDivergenceError(
                f"step {obs.step_index}: provenance={obs.provenance.value} "
                f"before perturbation_index={perturbation_index}; "
                f"silent mode transition invalidates attribution"
            )

        if obs.payload_hash() != recorded.observation_hash:
            raise ReplayDivergenceError(
                f"step {obs.step_index}: observation hash "
                f"{obs.payload_hash()[:12]} != recorded "
                f"{recorded.observation_hash[:12]}; "
                f"cache substitution detected"
            )

        if obs.matched_record_hash != recorded.observation_hash:
            raise ReplayDivergenceError(
                f"step {obs.step_index}: matched_record_hash does not equal "
                f"recorded hash; fuzzy cache key collision"
            )


def validate_counterfactual_report(
    replay: list[Observation],
    record: list[RecordedStep],
    perturbation_index: int,
    mode: ReplayMode,
    claimed_attribution: str,
) -> str:
    enforce_observational_prefix(replay, record, perturbation_index, mode)

    transitions = [
        o for o in replay
        if o.step_index < perturbation_index
        and o.provenance is not ObservationProvenance.RECORDED
    ]
    if transitions:
        raise ReplayDivergenceError(
            f"cannot attribute delta to {claimed_attribution!r}: "
            f"{len(transitions)} observation(s) diverged from record before "
            f"perturbation; replay is a new causal trajectory, not a counterfactual"
        )

    return claimed_attribution
