# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distinguish-tombstone-propagation-from-byte-level-erasure-in-vector-stores-and-agent-scratchpads.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distinguish-tombstone-propagation-from-byte-level-erasure-in-vector-stores-and-agent-scratchpads.warrant.json
# Markdown SHA-256:   bfbcdf827f84e048d660194e6dd57b7f5730be65b2b1925d3d42aabd6cf27cfa
# Code AST SHA-256:   e20653572c59feeb65c390b32c8baecd967f598410f1694087b4674cf8ede1ec
# Verified Classes:   ErasureProofError, ErasureState, IndexArtifact, ScratchpadInventory, ErasureRequest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ErasureProofError(RuntimeError):
    """Raised when an erasure proof cannot be validly emitted."""


class ErasureState(Enum):
    VERIFIED = "ERASURE_VERIFIED"
    PENDING_COMPACTION = "ERASURE_PENDING_COMPACTION"
    TOMBSTONED_BUT_RECONSTRUCTABLE = "TOMBSTONED_BUT_RECONSTRUCTABLE"
    INCOMPLETE = "ERASURE_INCOMPLETE"


@dataclass
class IndexArtifact:
    format: str                      # "hnsw" | "ivf_pq" | "flat"
    epoch: int
    compacted_epoch: int
    residual_pq_codes_present: bool
    neighbor_edges_present: bool


@dataclass
class ScratchpadInventory:
    snapshot_generations: list[int]
    purged_at_generation: int
    wal_segments_retained: bool


@dataclass
class ErasureRequest:
    subject_id: str
    index: IndexArtifact
    scratchpad: ScratchpadInventory
    embedding_model_public: bool
    per_subject_salt_destroyed: bool
    proof_manifest: dict = field(default_factory=dict)


def evaluate_erasure(req: ErasureRequest) -> ErasureState:
    idx, sp = req.index, req.scratchpad

    # Snapshot generations older than the purge are still readable -> incomplete.
    stale_snapshots = [g for g in sp.snapshot_generations if g < sp.purged_at_generation]
    if stale_snapshots or sp.wal_segments_retained:
        raise ErasureProofError(
            f"subject {req.subject_id}: unenumerated durable copies survive "
            f"(stale_snapshots={stale_snapshots}, wal={sp.wal_segments_retained})"
        )

    # Approximate index with uncompacted neighbor edges -> tombstone only.
    if idx.format in ("hnsw", "ivf_pq") and idx.neighbor_edges_present:
        if idx.compacted_epoch < idx.epoch:
            return ErasureState.PENDING_COMPACTION

    # Residual quantized codes + public model -> reconstructable.
    if idx.residual_pq_codes_present and req.embedding_model_public:
        if not req.per_subject_salt_destroyed:
            return ErasureState.TOMBSTONED_BUT_RECONSTRUCTABLE

    # Exact index, no residual, salt destroyed (or model non-invertible) -> valid.
    if idx.format == "flat" and not idx.residual_pq_codes_present:
        if req.per_subject_salt_destroyed or not req.embedding_model_public:
            req.proof_manifest = {
                "index_epoch": idx.epoch,
                "compacted_at": idx.compacted_epoch,
                "snapshot_generations_purged": sp.snapshot_generations,
                "salt_destroyed": req.per_subject_salt_destroyed,
                "digest": hashlib.sha256(
                    f"{req.subject_id}:{idx.epoch}:{idx.compacted_epoch}".encode()
                ).hexdigest(),
            }
            return ErasureState.VERIFIED

    raise ErasureProofError(
        f"subject {req.subject_id}: no valid erasure path — "
        f"format={idx.format}, pq={idx.residual_pq_codes_present}, "
        f"public_model={req.embedding_model_public}"
    )
