# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-memory-deletion-as-a-tombstone-rather-than-a-removal-the-resurrect-on-rewrite-boundary-in-explicit-memory-crud-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-memory-deletion-as-a-tombstone-rather-than-a-removal-the-resurrect-on-rewrite-boundary-in-explicit-memory-crud-apis.warrant.json
# Markdown SHA-256:   ce7b7ca09036d1d90f4c15dc8d44475a9208dc6369befabde81b5cd774a87f2c
# Code AST SHA-256:   0b07f7f01058e1bd8f6c6e66ff957ef3e88d0520017e8e0a81dafedebdfd7e77
# Verified Classes:   TombstoneViolation, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TombstoneViolation(RuntimeError):
    """Raised when a write would resurrect content that was hard-forgotten."""


def _norm(text: str) -> str:
    return " ".join(text.lower().split())


def _hash(text: str) -> str:
    return hashlib.sha256(_norm(text).encode()).hexdigest()


@dataclass
class MemoryStore:
    records: dict = field(default_factory=dict)
    # content-hash -> deletion scope; NOT subject to plain TTL
    tombstones: dict = field(default_factory=dict)

    def write(self, key: str, value: str, ttl: int | None = None) -> None:
        h = _hash(value)
        if h in self.tombstones:
            scope = self.tombstones[h]
            raise TombstoneViolation(
                f"write to {key!r} resurrects forgotten content "
                f"(hash={h[:12]}, forgotten_scope={scope!r}); "
                f"reject and log near-miss, do not prefer newer record"
            )
        self.records[key] = {"value": value, "ttl": ttl}

    def forget(self, key: str, hard: bool, scope: str = "") -> None:
        rec = self.records.pop(key, None)
        if rec is None:
            return
        if hard:
            self.tombstones[_hash(rec["value"])] = scope or key

    def assert_absent(self, value: str) -> None:
        """Post-condition: deletion is only verified by checking content,
        not by read-back of the key at forget time."""
        h = _hash(value)
        if h in self.tombstones:
            return
        for k, r in self.records.items():
            if _hash(r["value"]) == h:
                raise TombstoneViolation(
                    f"forgotten content reappeared under key {k!r}"
                )
