# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-memory-tool-schema-whose-forget-verb-is-a-soft-delete-tombstone-rather-than-a-hard-delete.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-memory-tool-schema-whose-forget-verb-is-a-soft-delete-tombstone-rather-than-a-hard-delete.warrant.json
# Markdown SHA-256:   75d8bd2758d07c485a54e29e6f86ce782a010b644eb0664417e8a9a34f3136a0
# Code AST SHA-256:   ea833631ebe9c40c5eb3369bf105048fd250708ba1229ac1249d53f44739d270
# Verified Classes:   TombstoneLeakError, BeliefState, MemoryBelief, ForgetAwareMemory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class TombstoneLeakError(RuntimeError):
    """Raised when a read path returns a key the agent has tombstoned."""


class BeliefState(Enum):
    PRESENT = "present"
    TOMBSTONED_UNVERIFIED = "tombstoned_unverified"
    PURGED_VERIFIED = "purged_verified"


@dataclass
class MemoryBelief:
    key: str
    state: BeliefState = BeliefState.PRESENT
    verified_paths: set = field(default_factory=set)


class ForgetAwareMemory:
    """Wraps a read/write/forget store that may implement soft-delete."""

    READ_PATHS = ("exact", "semantic", "versioned", "distilled")

    def __init__(self, store, schema_paths: tuple[str, ...]):
        self.store = store
        self.schema_paths = schema_paths
        self.beliefs: dict[str, MemoryBelief] = {}

    def forget(self, key: str) -> MemoryBelief:
        ack = self.store.forget(key)
        if not ack.get("ok"):
            raise TombstoneLeakError(f"forget({key}) rejected: {ack}")
        # Ack is visibility-scoped, NOT proof of unreachability.
        belief = MemoryBelief(key=key, state=BeliefState.TOMBSTONED_UNVERIFIED)
        self.beliefs[key] = belief
        self._probe_all_paths(belief)
        return belief

    def _probe_all_paths(self, belief: MemoryBelief) -> None:
        for path in self.schema_paths:
            hit = self.store.read(belief.key, path=path, include_deleted=True)
            if hit is not None:
                # Leak: this path still surfaces the tombstone.
                raise TombstoneLeakError(
                    f"key {belief.key!r} still reachable via path {path!r} "
                    f"after forget; belief cannot be upgraded to PURGED_VERIFIED"
                )
            belief.verified_paths.add(path)
        belief.state = BeliefState.PURGED_VERIFIED

    def read(self, key: str, path: str) -> Optional[str]:
        value = self.store.read(key, path=path)
        belief = self.beliefs.get(key)
        if value is not None and belief is not None and belief.state is not BeliefState.PRESENT:
            # Retrieval resurrection: refuse to re-accept silently.
            raise TombstoneLeakError(
                f"read({key!r}, path={path!r}) returned a value for a key "
                f"in state {belief.state.value}; re-issue forget and re-probe"
            )
        return value

    def handoff_payload(self, keys: list[str]) -> dict:
        out = {}
        for k in keys:
            b = self.beliefs.get(k)
            if b is not None and b.state is not BeliefState.PRESENT:
                continue  # never serialize tombstoned values across a boundary
            out[k] = self.store.read(k, path="exact")
        return out
