# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-forget-tombstone-free-erasure-and-the-provenance-quorum-invariant-in-write-forget-memory-tools.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-forget-tombstone-free-erasure-and-the-provenance-quorum-invariant-in-write-forget-memory-tools.warrant.json
# Markdown SHA-256:   b622820a967c2273d09d206d83df16703531f107ca1f4d424973cd2f900fa771
# Code AST SHA-256:   e0859039165e61519b9f65c9f824a458655c79d1599a8e9fb0a7a6f6c58ff678
# Verified Classes:   ErasureClosureIncomplete, ForgetStatus, Record
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class ErasureClosureIncomplete(RuntimeError):
    """Raised when a forget cannot prove its full erasure closure is erasable."""
    pass


class ForgetStatus(Enum):
    COMMITTED = "committed"
    BLOCKED = "blocked"


@dataclass
class Record:
    record_id: str
    namespace: str
    content: str
    provenance: list[str] = field(default_factory=list)
    source_excerpt: str | None = None
    reconstructible: bool = True


def enumerate_erasure_closure(
    target_id: str,
    store: dict[str, Record],
    peer_visible: set[str],
) -> tuple[set[str], set[str]]:
    """Return (local_closure, unerasable_members).

    Closure = transitive provenance descendants in ANY namespace, plus any
    record whose source_excerpt reconstructs a closure member.
    """
    closure: set[str] = set()
    frontier = [target_id]
    while frontier:
        rid = frontier.pop()
        if rid in closure:
            continue
        closure.add(rid)
        rec = store.get(rid)
        if rec is None:
            continue
        # descendants: records citing rid as provenance
        for other in store.values():
            if rid in other.provenance and other.record_id not in closure:
                frontier.append(other.record_id)
        # reconstruction edges: any record whose excerpt overlaps content
        if rec.content and rec.content[:32] in (other.source_excerpt or "" for other in store.values()):
            for other in store.values():
                if rec.content[:32] and rec.content[:32] in (other.source_excerpt or ""):
                    if other.record_id not in closure:
                        frontier.append(other.record_id)

    unerasable = {rid for rid in closure if store.get(rid) and store[rid].namespace not in peer_visible}
    return closure, unerasable


def forget(
    target_id: str,
    store: dict[str, Record],
    peer_visible: set[str],
    erasure_warrants: set[str],
) -> ForgetStatus:
    closure, unerasable = enumerate_erasure_closure(target_id, store, peer_visible)

    # Foreign-namespace members require an erasure warrant naming the namespace.
    for rid in closure:
        rec = store.get(rid)
        if rec and rec.namespace not in peer_visible:
            if rec.namespace not in erasure_warrants:
                raise ErasureClosureIncomplete(
                    f"forget({target_id}) blocked: closure member {rid} in "
                    f"namespace {rec.namespace!r} has no erasure warrant. "
                    f"Closure size={len(closure)}; enumerate and escalate, do not retry."
                )

    # Any member classified reconstructible but not erasable is a resurrection seed.
    for rid in closure:
        rec = store.get(rid)
        if rec and rec.reconstructible and rec.namespace not in peer_visible:
            raise ErasureClosureIncomplete(
                f"forget({target_id}) blocked: reconstructible member {rid} "
                f"cannot be purged in this store; erasure not achievable."
            )

    # All closure members erasable: purge bytes, edges, and excerpts atomically.
    for rid in closure:
        store.pop(rid, None)
    return ForgetStatus.COMMITTED
