# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-ttl-expired-memory-from-an-explicitly-forgotten-one-when-both-resolve-to-the-same-absence.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-ttl-expired-memory-from-an-explicitly-forgotten-one-when-both-resolve-to-the-same-absence.warrant.json
# Markdown SHA-256:   0f4fe51adee4f771b46e1ffd5a99a32497597aa80042bd8f55ab7cc0ae4ccf81
# Code AST SHA-256:   0a7b46e35201be4c8c26e0939b1916b1599e23f61f01f75389f318bd22993991
# Verified Classes:   MemoryState, ResurrectionError, TombstoneMissingError, Tombstone, Entry, ScopedMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class MemoryState(Enum):
    PRESENT = "present"
    EXPIRED = "expired"
    FORGOTTEN = "forgotten"
    UNKNOWN_ABSENT = "unknown_absent"


class ResurrectionError(RuntimeError):
    """Raised when a write would resurrect an explicitly forgotten entry."""


class TombstoneMissingError(RuntimeError):
    """Raised when a sensitive scope cannot prove absence provenance."""


@dataclass(frozen=True)
class Tombstone:
    scope: str
    key: str
    forgotten_at: float
    reason: str
    actor: str


@dataclass
class Entry:
    value: str
    written_at: float
    expires_at: float


class ScopedMemory:
    def __init__(self) -> None:
        self._data: dict[tuple[str, str], Entry] = {}
        self._tombstones: dict[tuple[str, str], Tombstone] = {}
        self._sensitive_scopes: set[str] = set()

    def mark_sensitive(self, scope: str) -> None:
        self._sensitive_scopes.add(scope)

    def write(self, scope: str, key: str, value: str, ttl: float) -> None:
        tomb = self._tombstones.get((scope, key))
        if tomb is not None and scope in self._sensitive_scopes:
            raise ResurrectionError(
                f"refusing to write {scope}/{key}: forgotten at "
                f"{tomb.forgotten_at} by {tomb.actor} ({tomb.reason})"
            )
        now = time.time()
        self._data[(scope, key)] = Entry(value=value, written_at=now, expires_at=now + ttl)

    def forget(self, scope: str, key: str, reason: str, actor: str) -> None:
        now = time.time()
        self._data.pop((scope, key), None)
        self._tombstones[(scope, key)] = Tombstone(
            scope=scope, key=key, forgotten_at=now, reason=reason, actor=actor
        )

    def read(self, scope: str, key: str) -> tuple[MemoryState, Optional[str]]:
        now = time.time()
        tomb = self._tombstones.get((scope, key))
        entry = self._data.get((scope, key))

        if tomb is not None:
            # A tombstone postdates any surviving entry only if the entry is older.
            if entry is None or entry.written_at < tomb.forgotten_at:
                return MemoryState.FORGOTTEN, None

        if entry is not None:
            if now < entry.expires_at:
                return MemoryState.PRESENT, entry.value
            # Physically present but logically expired: never return the value.
            return MemoryState.EXPIRED, None

        if scope in self._sensitive_scopes and tomb is None:
            # Sensitive scope, no data, no tombstone: cannot prove provenance.
            raise TombstoneMissingError(
                f"sensitive scope {scope!r} has no tombstone for {key!r}; "
                "absence provenance is unprovable"
            )

        return MemoryState.UNKNOWN_ABSENT, None


def rederive_or_fail(mem: ScopedMemory, scope: str, key: str) -> str:
    state, value = mem.read(scope, key)
    if state is MemoryState.PRESENT:
        return value  # type: ignore[return-value]
    if state is MemoryState.EXPIRED:
        return "recomputed"
    if state is MemoryState.FORGOTTEN:
        raise ResurrectionError(
            f"{scope}/{key} was explicitly forgotten; re-derivation is forbidden"
        )
    # UNKNOWN_ABSENT: caller must decide; refuse to guess.
    raise TombstoneMissingError(
        f"cannot re-derive {scope}/{key}: absence provenance unknown"
    )
