# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-tool-ttl-expiry-as-a-tombstone-rather-than-a-deletion-and-why-the-distinction-bounds-every-downs.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-tool-ttl-expiry-as-a-tombstone-rather-than-a-deletion-and-why-the-distinction-bounds-every-downs.warrant.json
# Markdown SHA-256:   a764298fc389aef7f6a8f01da5797c7274f97ffd930fe1e477a43927b5e3eeac
# Code AST SHA-256:   864ed753d5c7147c3a1326645891ac2e9ed492d7df436e0f8d21d6a6ccf62d53
# Verified Classes:   TombstoneReason, ResurrectionForbidden, Tombstone, WriteIntent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class TombstoneReason(str, Enum):
    TTL_EXPIRY = "ttl_expiry"
    AGENT_DELETE = "agent_delete"
    OPERATOR_DELETE = "operator_delete"


class ResurrectionForbidden(RuntimeError):
    """Raised when a write would resurrect a key whose tombstone forbids it."""


@dataclass(frozen=True)
class Tombstone:
    key: str
    reason: TombstoneReason
    at: float  # monotonic timestamp of deletion


@dataclass(frozen=True)
class WriteIntent:
    key: str
    body: dict
    supersedes_tombstone: Optional[float] = None
    reason: Optional[str] = None  # "reassert" | "schema_migration"


REASSERTABLE = {TombstoneReason.TTL_EXPIRY}
TERMINAL = {TombstoneReason.AGENT_DELETE, TombstoneReason.OPERATOR_DELETE}


def gate_write(intent: WriteIntent, tombstone: Optional[Tombstone]) -> None:
    """Enforce the tombstone-aware write boundary.

    A None tombstone means the key never existed: write is free.
    A TTL_EXPIRY tombstone permits re-assert only with explicit provenance.
    A terminal tombstone forbids agent-side re-write entirely.
    """
    if tombstone is None:
        return

    if tombstone.reason in TERMINAL:
        raise ResurrectionForbidden(
            f"key={intent.key!r} carries terminal tombstone "
            f"reason={tombstone.reason.value!r} at={tombstone.at}; "
            f"agent-side re-write forbidden, escalate to operator"
        )

    if tombstone.reason in REASSERTABLE:
        if intent.supersedes_tombstone != tombstone.at:
            raise ResurrectionForbidden(
                f"key={intent.key!r} has TTL tombstone at={tombstone.at} "
                f"but write provenance supersedes_tombstone="
                f"{intent.supersedes_tombstone!r}; re-assert must name the tombstone"
            )
        if intent.reason not in {"reassert", "schema_migration"}:
            raise ResurrectionForbidden(
                f"key={intent.key!r} re-assert requires reason in "
                f"{{'reassert','schema_migration'}}, got {intent.reason!r}"
            )
        return

    raise ResurrectionForbidden(
        f"key={intent.key!r} has unrecognized tombstone reason "
        f"{tombstone.reason!r}; refusing write under unknown semantics"
    )


def write_memory(store, intent: WriteIntent) -> None:
    tombstone = store.audit(intent.key)  # explicit ledger consult, not read()
    gate_write(intent, tombstone)
    store.write(intent.key, intent.body, supersedes=intent.supersedes_tombstone)
