# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-right-to-erasure-deletion-as-complete-when-the-erased-vector-survives-as-an-unreferenced-tombstone-in-a.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-right-to-erasure-deletion-as-complete-when-the-erased-vector-survives-as-an-unreferenced-tombstone-in-a.warrant.json
# Markdown SHA-256:   2c67db18ae0a9696b6cb9d306751d673d6652fbf1c2269b8383a688384f5ba8f
# Code AST SHA-256:   79afba21a701bcf13667a75e136d7d3bde2966a000e80345b9fe360626203395
# Verified Classes:   ErasureMethod, IndexProfile, ErasureReceipt, ErasureIncompleteError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ErasureMethod(Enum):
    # Ordered by strength. TOMBSTONE is referential only.
    TOMBSTONE = 1
    EDGE_REPAIR = 2
    FULL_REBUILD = 3


@dataclass
class IndexProfile:
    is_approximate: bool
    has_snapshots: bool
    snapshot_epochs: list = field(default_factory=list)
    uses_trained_codebook: bool = False
    shared_across_subjects: bool = True


@dataclass
class ErasureReceipt:
    subject_id: str
    method: ErasureMethod
    journal_replayed_on_restore: bool
    invalidated_snapshot_epochs: list
    reid_risk_assessed: bool


class ErasureIncompleteError(RuntimeError):
    """Raised when a claimed erasure does not satisfy representational erasure."""


def validate_erasure(receipt: ErasureReceipt, profile: IndexProfile) -> None:
    """Precondition gate: refuse to report erasure complete unless all four
    conditions of validity hold for this store profile."""

    # Condition 1 (payload absence) is assumed checked by the caller; we cannot
    # verify it here. Conditions 2-4 are verified below.

    # Condition 2: routing absence. An approximate index retains the erased
    # node's edges unless repaired or rebuilt.
    if profile.is_approximate and receipt.method is ErasureMethod.TOMBSTONE:
        raise ErasureIncompleteError(
            f"subject {receipt.subject_id}: tombstone on approximate index "
            f"leaves edges intact; erased vector still routes queries. "
            f"Requires EDGE_REPAIR or FULL_REBUILD."
        )

    # Condition 3: reconstruction resistance. A codebook trained on the erased
    # subject encodes its statistics and cannot be patched.
    if profile.uses_trained_codebook and receipt.method is not ErasureMethod.FULL_REBUILD:
        raise ErasureIncompleteError(
            f"subject {receipt.subject_id}: index uses a trained codebook "
            f"contaminated by the erased vector; only FULL_REBUILD satisfies "
            f"reconstruction resistance."
        )
    if profile.is_approximate and receipt.method is ErasureMethod.EDGE_REPAIR:
        if not receipt.reid_risk_assessed:
            raise ErasureIncompleteError(
                f"subject {receipt.subject_id}: edge repair leaves residual "
                f"structural information; a re-identification risk assessment "
                f"is required before claiming completion."
            )

    # Condition 4: ancestral invalidation. Snapshots predating erasure must be
    # invalidated or covered by a replayed erasure journal.
    if profile.has_snapshots:
        uncovered = set(profile.snapshot_epochs) - set(receipt.invalidated_snapshot_epochs)
        if uncovered and not receipt.journal_replayed_on_restore:
            raise ErasureIncompleteError(
                f"subject {receipt.subject_id}: snapshots {sorted(uncovered)} "
                f"predate erasure and are not covered by a replayed erasure "
                f"journal; restore will resurrect the subject."
            )


def issue_receipt(
    subject_id: str,
    method: ErasureMethod,
    profile: IndexProfile,
    journal_replayed_on_restore: bool,
    invalidated_snapshot_epochs: list,
    reid_risk_assessed: bool,
) -> dict:
    receipt = ErasureReceipt(
        subject_id=subject_id,
        method=method,
        journal_replayed_on_restore=journal_replayed_on_restore,
        invalidated_snapshot_epochs=invalidated_snapshot_epochs,
        reid_risk_assessed=reid_risk_assessed,
    )
    validate_erasure(receipt, profile)  # raises ErasureIncompleteError on failure
    digest = hashlib.sha256(
        f"{subject_id}:{method.name}:{sorted(invalidated_snapshot_epochs)}".encode()
    ).hexdigest()[:16]
    return {
        "subject": subject_id,
        "erased": True,
        "method": method.name,
        "receipt_digest": digest,
        "conditions_verified": ["payload", "routing", "reconstruction", "ancestral"],
    }
