# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-memory-tool-forget-as-a-tombstone-rather-than-an-absence.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-memory-tool-forget-as-a-tombstone-rather-than-an-absence.warrant.json
# Markdown SHA-256:   1d820f0d8c0b85ea20202cdf924dcd49a7d416ffee577dfc2bc156eafde613bc
# Code AST SHA-256:   1499322a3161144208531a8cc9218fe7fb410ffb06bd3ed6839863c22d94e5f7
# Verified Classes:   MemoryResurrectionError, ReadKind, ReadResult, ScopedMemory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class MemoryResurrectionError(RuntimeError):
    """Raised when an agent attempts to refill a key whose empty read may be a tombstone."""


class ReadKind(Enum):
    PRESENT = "present"
    ABSENT = "absent"        # never written
    TOMBSTONED = "tombstoned"  # explicitly forgotten
    UNKNOWN = "unknown"      # API collapsed absence and tombstone; no sibling witness


@dataclass(frozen=True)
class ReadResult:
    kind: ReadKind
    value: Optional[str] = None


class ScopedMemory:
    """Memory tool with scoped keys. Note: read() collapses absent/tombstoned by default."""

    def __init__(self) -> None:
        self._store: dict[tuple[str, str], str] = {}
        self._tombstones: dict[tuple[str, str], str] = {}

    def write(self, scope: str, key: str, value: str) -> None:
        if (scope, key) in self._tombstones:
            raise MemoryResurrectionError(
                f"write to tombstoned key {scope}/{key} requires explicit override"
            )
        self._store[(scope, key)] = value

    def forget(self, scope: str, key: str, reason: str) -> None:
        self._store.pop((scope, key), None)
        self._tombstones[(scope, key)] = reason

    def read(self, scope: str, key: str) -> ReadResult:
        if (scope, key) in self._store:
            return ReadResult(ReadKind.PRESENT, self._store[(scope, key)])
        if (scope, key) in self._tombstones:
            return ReadResult(ReadKind.TOMBSTONED)
        return ReadResult(ReadKind.ABSENT)


def refill_or_escalate(
    mem: ScopedMemory,
    scope: str,
    key: str,
    rederive_is_stochastic: bool,
    override: bool = False,
) -> Optional[str]:
    """The guarded resume path. Refuses to refill a possibly-tombstoned stochastic key."""
    result = mem.read(scope, key)

    if result.kind is ReadKind.PRESENT:
        return result.value

    if result.kind is ReadKind.TOMBSTONED:
        if not override:
            raise MemoryResurrectionError(
                f"{scope}/{key} was explicitly forgotten; refusing to re-derive without override"
            )
        # override path: caller has taken responsibility; write is allowed only here
        return None

    if result.kind is ReadKind.ABSENT:
        return None  # safe to re-derive and write

    # UNKNOWN: API gave no witness. If re-derivation is stochastic, refilling is unsafe.
    if rederive_is_stochastic:
        raise MemoryResurrectionError(
            f"empty read on {scope}/{key} is UNKNOWN (no tombstone witness); "
            f"stochastic re-derivation would risk resurrecting deleted state"
        )
    return None
