# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-acknowledges-a-forget-directive-but-its-derived-episodic-embeddings-remain-queryable-through-approximate-nearest-neighbo.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-acknowledges-a-forget-directive-but-its-derived-episodic-embeddings-remain-queryable-through-approximate-nearest-neighbo.warrant.json
# Markdown SHA-256:   846cacb0b8564f4be7b6a787606e4014e336062572fcf53537d3eddbc3a4d429
# Code AST SHA-256:   70ccd885273209e79bfaea1641a447d19239510bcaaeff4a03064e1d57af3a19
# Verified Classes:   ErasureVerificationError, ErasureStatus, ForgetDirective, MemoryStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ErasureVerificationError(RuntimeError):
    """Raised when an erasure claim is not backed by a live semantic probe."""
    pass


class ErasureStatus(Enum):
    SUPPRESSED = "suppressed"   # payload hidden, influence may persist
    EXCISED = "excised"         # graph-repaired, canaries pass
    BLOCKED = "blocked"         # excision requested but not achievable


@dataclass
class ForgetDirective:
    record_id: str
    scope: str                  # "suppression" | "excision"
    canary_hashes: list[str]    # salted hashes of known top-hit queries


@dataclass
class MemoryStore:
    raw: dict = field(default_factory=dict)
    # ANN index: node_id -> (neighbors, live)
    ann: dict = field(default_factory=dict)
    centroids: dict = field(default_factory=dict)

    def suppress(self, record_id: str) -> None:
        self.raw.pop(record_id, None)
        if record_id in self.ann:
            neighbors, _ = self.ann[record_id]
            self.ann[record_id] = (neighbors, False)  # tombstone: still a hop

    def excise(self, record_id: str) -> None:
        self.raw.pop(record_id, None)
        node = self.ann.pop(record_id, None)
        if node is not None:
            neighbors, _ = node
            for n in neighbors:
                if n in self.ann:
                    nbrs, live = self.ann[n]
                    self.ann[n] = ([x for x in nbrs if x != record_id], live)
        # centroids that included this vector must be recomputed upstream
        for k in list(self.centroids):
            if record_id in self.centroids[k]:
                raise ErasureVerificationError(
                    f"centroid {k} still references {record_id}; recompute before claiming excision"
                )


def verify_erasure(store: MemoryStore, directive: ForgetDirective,
                   probe, reconstruction_distance: float) -> ErasureStatus:
    """
    probe(canary_hash) -> list[(live_record_id, distance)]
    Returns the *weakest* status that is actually supported by evidence.
    """
    if directive.scope == "excision":
        # 1. raw must be gone
        if directive.record_id in store.raw:
            raise ErasureVerificationError(
                f"raw record {directive.record_id} still present; cannot claim excision"
            )
        # 2. ANN node must be absent, not tombstoned
        node = store.ann.get(directive.record_id)
        if node is not None and node[1] is False:
            # tombstoned -> still a traversal hop -> influence leak
            raise ErasureVerificationError(
                f"record {directive.record_id} is tombstoned, not excised; "
                f"HNSW traversal-hop leak remains"
            )
        # 3. semantic canary replay must clear the reconstruction floor
        for h in directive.canary_hashes:
            hits = probe(h)
            for live_id, dist in hits:
                if dist < reconstruction_distance:
                    raise ErasureVerificationError(
                        f"canary {h[:8]} reconstructs {live_id} at distance "
                        f"{dist:.3f} < {reconstruction_distance}; excision unproven"
                    )
        return ErasureStatus.EXCISED

    if directive.scope == "suppression":
        store.suppress(directive.record_id)
        # suppression never earns the "excised" label
        return ErasureStatus.SUPPRESSED

    raise ErasureVerificationError(f"unknown erasure scope: {directive.scope}")


def commit_erasure(store: MemoryStore, directive: ForgetDirective,
                   probe, reconstruction_distance: float = 0.15) -> dict:
    """Top-level entry: refuse to emit 'erased' unless the probe passes."""
    try:
        status = verify_erasure(store, directive, probe, reconstruction_distance)
    except ErasureVerificationError as e:
        # hard stop: report blocked, never aggregate into 'erased'
        return {
            "record_id": directive.record_id,
            "status": ErasureStatus.BLOCKED.value,
            "reason": str(e),
            "verification_method": "semantic_canary",
        }
    if status is ErasureStatus.EXCISED:
        return {
            "record_id": directive.record_id,
            "status": "erased",
            "verification_method": "semantic_canary",
        }
    return {
        "record_id": directive.record_id,
        "status": status.value,
        "verification_method": "semantic_canary",
        "note": "suppression only; influence may persist via ANN hops and centroids",
    }
