# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-write-that-the-retention-policy-cannot-yet-adjudicate.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-write-that-the-retention-policy-cannot-yet-adjudicate.warrant.json
# Markdown SHA-256:   f45bf9597333dca67e8d5dac5f23ddc81dd1a7f7c20b2a1605a0fa47e8fe86fb
# Code AST SHA-256:   c9be18660b33f95ca3ed5878846ae6861b4764c4996910d8e4caf775c37e0311
# Verified Classes:   RetentionState, UnadjudicableWriteError, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class RetentionState(Enum):
    RESOLVED = "resolved"
    QUARANTINED = "retention_unresolved"
    CONFLICT = "retention_conflict"


class UnadjudicableWriteError(RuntimeError):
    """Raised when a memory write cannot be assigned a valid retention class
    and the caller attempts to treat it as durable."""


@dataclass
class MemoryRecord:
    content: str
    classification: str
    jurisdiction: Optional[str]
    expires_at: Optional[int]
    derived_expires_at: Optional[int] = None
    state: RetentionState = RetentionState.QUARANTINED


RULE_TABLE = {
    ("pii:contact_preference", "EU"): 30,
    ("pii:contact_preference", "US"): 365,
}


def remember(record: MemoryRecord, now: int) -> MemoryRecord:
    key = (record.classification, record.jurisdiction)
    ttl = RULE_TABLE.get(key)
    if ttl is None:
        # No rule matched: quarantine, do NOT default-TTL, do NOT drop.
        record.state = RetentionState.QUARANTINED
        record.expires_at = None
        return record
    record.expires_at = now + ttl
    record.state = RetentionState.RESOLVED
    return record


def recall(record: MemoryRecord) -> MemoryRecord:
    if record.state is RetentionState.QUARANTINED:
        # Content is retrievable for the current turn but marked provisional.
        # Caller MUST NOT promote this to a durable write or outbound action.
        return record
    if record.state is RetentionState.CONFLICT:
        raise UnadjudicableWriteError(
            f"record has conflicting expiry: "
            f"expires_at={record.expires_at} derived={record.derived_expires_at}"
        )
    return record


def expiry_sweep(records: list[MemoryRecord], now: int) -> list[MemoryRecord]:
    """Per-record fault isolation: one conflict must not abort the batch."""
    survivors = []
    for r in records:
        if r.state is RetentionState.QUARANTINED:
            survivors.append(r)  # never auto-expire an unresolved record
            continue
        if r.derived_expires_at is not None and r.expires_at != r.derived_expires_at:
            r.state = RetentionState.CONFLICT
            survivors.append(r)
            continue
        if r.expires_at is not None and r.expires_at <= now:
            continue  # expired, drop
        survivors.append(r)
    return survivors


def promote_to_durable(record: MemoryRecord, now: int) -> MemoryRecord:
    """Agent-side guard: a provisional fact must not be laundered into a
    durable write without re-derivation."""
    if record.state is RetentionState.QUARANTINED:
        raise UnadjudicableWriteError(
            "cannot promote quarantined record to durable memory; "
            "re-derive from source or record an explicit drop"
        )
    return remember(record, now)
