# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-tombstoned-from-never-written-memory-keys-under-verifiable-deletion.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-tombstoned-from-never-written-memory-keys-under-verifiable-deletion.warrant.json
# Markdown SHA-256:   7785568a856637e57805675112163fb4baa0c7eca19222b80da95371baabc82e
# Code AST SHA-256:   80a7577ed0a6094506e1e5a62f9563d195cbc412da094b68592bfcc5260c9818
# Verified Classes:   MemoryStateError, ReadState, ReadResult
# 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 MemoryStateError(RuntimeError):
    """Raised when read/write/forget semantics are violated at a scope boundary."""


class ReadState(Enum):
    PRESENT = "present"
    TOMBSTONED = "tombstoned"   # explicitly forgotten, receipt exists
    EXPIRED = "expired"          # retention/TTL elapsed
    OUT_OF_SCOPE = "out_of_scope"  # written, but not visible under this scope
    NEVER_WRITTEN = "never_written"


@dataclass(frozen=True)
class ReadResult:
    state: ReadState
    value: Optional[bytes] = None
    receipt_hash: Optional[str] = None
    deleted_at: Optional[str] = None


def guarded_write(
    key: str,
    scope: str,
    value: bytes,
    read_fn,
    tombstone_index,
) -> None:
    """
    Write a memory key, refusing to resurrect a forgotten key.

    A bare None read is NOT permission to write. We must consult the
    tombstone index and confirm the read state before mutating.
    """
    result: ReadResult = read_fn(key, scope)

    if result.state is ReadState.TOMBSTONED:
        raise MemoryStateError(
            f"refusing to resurrect forgotten key {key!r} in scope {scope!r}; "
            f"deletion receipt {result.receipt_hash} at {result.deleted_at}. "
            f"Obtain explicit re-authorization before writing."
        )

    if result.state is ReadState.OUT_OF_SCOPE:
        raise MemoryStateError(
            f"key {key!r} exists outside scope {scope!r}; retry read at the "
            f"write scope before concluding absence."
        )

    if result.state is ReadState.NEVER_WRITTEN:
        # Only now is a create safe.
        tomb = tombstone_index.lookup(key, scope)
        if tomb is not None and not tomb.recreated_authorized:
            raise MemoryStateError(
                f"tombstone for {key!r}/{scope!r} present in index but read "
                f"reported NEVER_WRITTEN; read path is inconsistent with "
                f"deletion log. Refusing write."
            )

    # PRESENT (overwrite) or confirmed-absent create proceeds.
    _commit(key, scope, value)


def _commit(key: str, scope: str, value: bytes) -> None:
    # Backend write; omitted.
    ...
