# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-an-explicit-forget-call-because-the-decay-weighted-salience-of-the-target-memory-exceeds-the-deleti.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-an-explicit-forget-call-because-the-decay-weighted-salience-of-the-target-memory-exceeds-the-deleti.warrant.json
# Markdown SHA-256:   b8cd63920f8a2d70d78605107528c4f4a4a44d432e3f917fad687d6903458635
# Code AST SHA-256:   4604bcecf71befa155ebe1ca071f2bbd3e7b9e663afa62cdc1c3c84bbfac72f8
# Verified Classes:   StaleForgetWarrantError, MemoryRecord, ForgetWarrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleForgetWarrantError(RuntimeError):
    """Raised when a forget warrant predates the target's last reinforcement."""
    pass


@dataclass
class MemoryRecord:
    memory_id: str
    salience: float
    last_reinforced: float
    reinforcement_count: int
    pinned: bool = False


@dataclass
class ForgetWarrant:
    memory_id: str
    warrant_ts: float
    issuer: str


def honor_forget(record: MemoryRecord, warrant: ForgetWarrant, now: float) -> bool:
    """Apply a forget warrant only if it is fresher than the last reinforcement.

    Returns True if the tombstone was written, raises StaleForgetWarrantError
    if the warrant's premise has been invalidated by subsequent use.
    """
    if record.pinned:
        raise StaleForgetWarrantError(
            f"memory {record.memory_id} is pinned; forget refused regardless of warrant age"
        )

    # The decisive comparison: warrant freshness vs. last reinforcement.
    if warrant.warrant_ts <= record.last_reinforced:
        raise StaleForgetWarrantError(
            "forget warrant is stale: "
            f"warrant_ts={warrant.warrant_ts} <= "
            f"last_reinforced={record.last_reinforced} "
            f"(reinforcement_count={record.reinforcement_count}, "
            f"salience_now={record.salience}); "
            "re-mint the warrant against current state before deletion"
        )

    # Fresh warrant: proceed to tombstone. In production this write must be
    # serialized on the same memory-id lock as the reinforcement increment.
    return True


def attempt_forget(record: MemoryRecord, warrant: ForgetWarrant, now: float) -> dict:
    try:
        honored = honor_forget(record, warrant, now)
    except StaleForgetWarrantError as exc:
        return {"status": "rejected", "reason": str(exc), "memory_id": record.memory_id}
    return {"status": "tombstoned" if honored else "noop", "memory_id": record.memory_id}
