# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-forget-and-how-does-erasure-compliance-collide-with-episodic-replay-in-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-forget-and-how-does-erasure-compliance-collide-with-episodic-replay-in-agent-memory.warrant.json
# Markdown SHA-256:   57429a33e2f84490d343922b85e103ec396626ba2e66b434f54a6259b7cee6d5
# Code AST SHA-256:   153e253cbe58af1aebae22b1d94184ff7d5ca52b298a6ee456fc5a25117dd758
# Verified Classes:   ErasureAttestationError, Episode, Ledger, MemoryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ErasureAttestationError(RuntimeError):
    """Raised when an erasure cannot be jointly attested as content-destroyed
    AND audit-preserving. Signals the agent to halt, not to retry blindly."""
    pass


@dataclass
class Episode:
    episode_id: str
    subject_ref: str
    ciphertext: bytes
    data_key_id: str
    commitment: str          # H(ciphertext), stored in ledger
    provenance_keys: set = field(default_factory=set)


@dataclass
class Ledger:
    entries: list = field(default_factory=list)
    merkle_root: Optional[str] = None

    def append(self, event: dict) -> None:
        self.entries.append(event)
        # root commits only to non-personal metadata + commitments, never payload
        h = hashlib.sha256()
        for e in self.entries:
            h.update(repr(sorted(e.items())).encode())
        self.merkle_root = h.hexdigest()


class MemoryStore:
    def __init__(self):
        self.episodes: dict[str, Episode] = {}
        self.keys: dict[str, bytes] = {}
        self.aggregates: dict[str, set] = {}  # agg_id -> provenance key ids
        self.ledger = Ledger()

    def erase_subject(self, subject_ref: str, audit_window_open: bool) -> dict:
        targets = [e for e in self.episodes.values() if e.subject_ref == subject_ref]
        if not targets:
            raise ErasureAttestationError(f"no episodes for subject {subject_ref!r}")

        key_ids = {e.data_key_id for e in targets}

        # Guard 1: commitment must not be a plaintext hash (oracle risk)
        for e in targets:
            if e.commitment == hashlib.sha256(subject_ref.encode()).hexdigest():
                raise ErasureAttestationError(
                    f"episode {e.episode_id} commits to plaintext subject_ref; "
                    "dictionary re-identification possible"
                )

        # Guard 2: audit window open => must crypto-shred, not row-delete
        if audit_window_open:
            for kid in key_ids:
                self.keys.pop(kid, None)  # destroy data key
            # invalidate aggregates whose provenance touched these keys
            stale = [a for a, prov in self.aggregates.items() if prov & key_ids]
            for a in stale:
                del self.aggregates[a]
            payload_present = any(
                e.data_key_id in self.keys for e in targets
            )
            if payload_present:
                raise ErasureAttestationError(
                    "key destruction incomplete; payload still decryptable"
                )
            event = {
                "type": "erasure",
                "subject": subject_ref,
                "episodes": [e.episode_id for e in targets],
                "invalidated_aggregates": stale,
                "mechanism": "crypto_shred",
            }
        else:
            for e in targets:
                del self.episodes[e.episode_id]
            event = {
                "type": "erasure",
                "subject": subject_ref,
                "episodes": [e.episode_id for e in targets],
                "mechanism": "full_delete",
            }

        self.ledger.append(event)

        # Guard 3: ledger must remain verifiable after erasure
        if self.ledger.merkle_root is None:
            raise ErasureAttestationError("ledger root missing post-erasure")

        return {"attested": True, "event": event, "ledger_root": self.ledger.merkle_root}
