# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-ttl-evicted-memory-reads-from-resurrecting-stale-facts-through-a-write-during-read-race-in-scoped-namespace-memory-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-ttl-evicted-memory-reads-from-resurrecting-stale-facts-through-a-write-during-read-race-in-scoped-namespace-memory-apis.warrant.json
# Markdown SHA-256:   e2d91af37c17c4370ae12cedf2287105a6cc79bbadb8410b07ac3df387b58512
# Code AST SHA-256:   ccf5fa9feb0022167218c561a62cd25e8a38a90e1ee627299adfebff5384d2e7
# Verified Classes:   MissReason, ResurrectionAttempt, Entry, GetResult
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class MissReason(Enum):
    NEVER_EXISTED = "never_existed"
    TTL_EXPIRED = "ttl_expired"
    SCOPE_OVERRIDE = "scope_override"


class ResurrectionAttempt(RuntimeError):
    """Raised when an agent tries to write a value it only holds in context
    after a ttl_expired miss, which would re-stamp a stale fact with a fresh TTL."""
    pass


@dataclass
class Entry:
    value: str
    timestamp: float
    ttl: float


@dataclass
class GetResult:
    status: str  # "hit" | "miss"
    reason: Optional[MissReason]
    entry: Optional[Entry]


def guarded_put(
    scope: str,
    key: str,
    value: str,
    ttl: float,
    now: float,
    last_read: GetResult,
    observed_in_this_turn: bool,
) -> Entry:
    # Invariant 1: a ttl_expired miss forbids reconstruction from context.
    if last_read.status == "miss" and last_read.reason is MissReason.TTL_EXPIRED:
        if not observed_in_this_turn:
            raise ResurrectionAttempt(
                f"Refusing put({scope!r}, {key!r}): value originates from stale "
                f"context after ttl_expired miss. Re-derive from a live tool."
            )

    # Invariant 2: scope-lattice monotonicity — a parent write must not be
    # newer than any resident child-scope entry for the same key.
    if last_read.status == "miss" and last_read.reason is MissReason.SCOPE_OVERRIDE:
        raise ResurrectionAttempt(
            f"Refusing put({scope!r}, {key!r}): a more-specific scope holds a "
            f"newer entry. Read the overriding scope instead of writing the parent."
        )

    return Entry(value=value, timestamp=now, ttl=ttl)


def agent_recover(
    scope: str,
    key: str,
    last_read: GetResult,
    context_value: Optional[str],
    now: float,
    ttl: float,
) -> Entry:
    if last_read.status == "hit":
        return last_read.entry

    if last_read.reason is MissReason.TTL_EXPIRED:
        # Must re-derive; context_value is a hypothesis, not a fact.
        if context_value is None:
            raise ResurrectionAttempt(
                f"No live source available for {key!r}; cannot safely reconstruct."
            )
        # observed_in_this_turn=False because it came from context, not a tool.
        return guarded_put(scope, key, context_value, ttl, now, last_read,
                           observed_in_this_turn=False)

    if last_read.reason is MissReason.NEVER_EXISTED:
        if context_value is None:
            raise ResurrectionAttempt(f"Nothing to write for {key!r}.")
        return guarded_put(scope, key, context_value, ttl, now, last_read,
                           observed_in_this_turn=True)

    raise ResurrectionAttempt(f"Unhandled miss reason: {last_read.reason}")
