# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-gdpr-erasure-tombstone-collides-with-an-in-flight-audit-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-gdpr-erasure-tombstone-collides-with-an-in-flight-audit-replay.warrant.json
# Markdown SHA-256:   41542f91707b10e9e54b695acc80c4c5f3946e249c2855c693b74899128a0698
# Code AST SHA-256:   fa836a04611ee17b470ef25a29019b2d4794d62bb80f2fd93355ab65d34d5e70
# Verified Classes:   ErasureReplayCollision, NodeState, AuditNode
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ErasureReplayCollision(RuntimeError):
    """Raised when a replay/resume needs plaintext of an ERASED node."""
    pass


class NodeState(Enum):
    PRESENT = "present"
    EMPTY = "empty"        # legitimately written empty payload
    ABSENT = "absent"      # never written
    ERASED = "erased"      # tombstoned; payload destroyed, commitment retained


@dataclass
class AuditNode:
    episode_id: str
    state: NodeState
    prev_hash: str
    stored_hash: str          # H(salt || payload); survives erasure as commitment
    payload: Optional[bytes]  # None when ERASED


def replay_for_resume(nodes: list[AuditNode], needed_episode: str) -> bytes:
    """
    Reconstruct the payload the agent needs to resume.
    Halts (fail-closed) if the needed node is ERASED: erasure forbids
    reconstructing it, and null is NOT a lawful substitute.
    """
    for node in nodes:
        if node.episode_id != needed_episode:
            continue
        if node.state is NodeState.ERASED:
            # Cannot invert the commitment; cannot legally fabricate.
            raise ErasureReplayCollision(
                f"episode {needed_episode} is ERASED; resume requires plaintext "
                f"that erasure destroyed. Halting for authorized re-derivation."
            )
        if node.state is NodeState.ABSENT:
            raise ErasureReplayCollision(
                f"episode {needed_episode} was never written; refusing to "
                f"resume on a phantom dependency."
            )
        if node.state is NodeState.EMPTY:
            return b""  # a real empty observation, distinct from ERASED
        assert node.payload is not None
        return node.payload
    raise ErasureReplayCollision(f"episode {needed_episode} not found in chain")


def verify_chain(nodes: list[AuditNode]) -> dict:
    """
    Verify tamper-evidence without laundering tombstones.
    Returns counts; never reports 'fully verified' when tombstones exist.
    """
    unverifiable = 0
    for i, node in enumerate(nodes):
        if i > 0 and node.prev_hash != nodes[i - 1].stored_hash:
            raise ErasureReplayCollision(
                f"chain break at {node.episode_id}: prev_hash mismatch"
            )
        if node.state is NodeState.ERASED:
            # commitment retained, content gone: link is unverifiable by design
            unverifiable += 1
    return {
        "links": len(nodes),
        "unverifiable_by_erasure": unverifiable,
        "fully_verified": unverifiable == 0,
    }
