# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-replayed-a2a-artifact-whose-artifactid-matches-but-whose-contenthash-was-minted-under-a-different-agentcard-protocolver.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-replayed-a2a-artifact-whose-artifactid-matches-but-whose-contenthash-was-minted-under-a-different-agentcard-protocolver.warrant.json
# Markdown SHA-256:   0ec3178626b89e622a17fcf48789a15ced6a360331d5d462723c47219e6a3477
# Code AST SHA-256:   7e28663e56be54ca314470cacc946f19d8dd34aa142a92e60e09c832e8b8f3e1
# Verified Classes:   ArtifactLineageError, Verdict, Emission, ArtifactLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Dict, Optional


class ArtifactLineageError(RuntimeError):
    """Raised when a replayed artifact cannot be safely reconciled against its prior emission."""
    pass


class Verdict(Enum):
    FIRST_EMISSION = "first_emission"
    IDEMPOTENT_REPLAY = "idempotent_replay"
    LINEAGE_SKEW = "lineage_skew"
    TAMPER = "tamper"


@dataclass(frozen=True)
class Emission:
    artifact_id: str
    content_hash: str
    protocol_version: str
    encoding: str


class ArtifactLedger:
    def __init__(self) -> None:
        # key: artifactId -> the full lineage tuple, never just the hash
        self._cache: Dict[str, Emission] = {}

    def validate(self, replay: Emission, *, artifact_id_immutable: bool) -> Verdict:
        prior: Optional[Emission] = self._cache.get(replay.artifact_id)

        if prior is None:
            self._cache[replay.artifact_id] = replay
            return Verdict.FIRST_EMISSION

        # Lineage predicate MUST run before any hash comparison.
        if (replay.protocol_version != prior.protocol_version
                or replay.encoding != prior.encoding):
            if artifact_id_immutable:
                raise ArtifactLineageError(
                    f"artifactId={replay.artifact_id!r} replayed under "
                    f"protocolVersion {prior.protocol_version!r}->{replay.protocol_version!r} "
                    f"or encoding {prior.encoding!r}->{replay.encoding!r}; "
                    f"hash comparison is undefined. Require fresh artifactId or "
                    f"signed migration attestation binding "
                    f"{prior.content_hash}->{replay.content_hash}."
                )
            return Verdict.LINEAGE_SKEW

        if replay.content_hash != prior.content_hash:
            return Verdict.TAMPER

        return Verdict.IDEMPOTENT_REPLAY


def handle_replay(ledger: ArtifactLedger, replay: Emission, *, artifact_id_immutable: bool) -> Verdict:
    verdict = ledger.validate(replay, artifact_id_immutable=artifact_id_immutable)
    if verdict is Verdict.TAMPER:
        # fail closed: quarantine, never overwrite the cached tuple
        raise ArtifactLineageError(
            f"contentHash mismatch for artifactId={replay.artifact_id!r} under "
            f"identical lineage {replay.protocol_version!r}/{replay.encoding!r}: "
            f"expected {ledger._cache[replay.artifact_id].content_hash}, "
            f"got {replay.content_hash}. Treat as mutation, not skew."
        )
    return verdict
