# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-memory-tool-forget-as-a-tombstone-rather-than-a-row-deletion-and-why-ttl-eviction-silently-violates-right-to-be-forgotte.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-memory-tool-forget-as-a-tombstone-rather-than-a-row-deletion-and-why-ttl-eviction-silently-violates-right-to-be-forgotte.warrant.json
# Markdown SHA-256:   18ace36f49d9a62b59b6870ea25f0b2f0308071eff5f2207c71d8cafb088befe
# Code AST SHA-256:   96f7b680f320356db75afc74e6b17f07ee2c6716c169b0f432149074d7f1effa
# Verified Classes:   ForgetState, ErasureObligationError, ForgetResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass
from enum import Enum


class ForgetState(str, Enum):
    DELETED = "deleted"
    PARTIAL = "partial"
    PENDING_COMPACTION = "pending_compaction"
    PENDING_REPLICATION = "pending_replication"
    UNPROVABLE = "unprovable"


class ErasureObligationError(RuntimeError):
    """Raised when a forget is certified without satisfying the lineage invariant."""


@dataclass(frozen=True)
class ForgetResult:
    state: ForgetState
    derived_scopes_cleared: frozenset[str]
    tombstone_minimized: bool
    replica_converged: bool


def certify_forget(result: ForgetResult, asserted_obligation: bool) -> ForgetState:
    """
    Decide whether a forget may be reported as satisfied.
    A TTL eviction that produces the same primary-read absence MUST NOT be
    certified as erasure when an obligation was asserted.
    """
    if not asserted_obligation:
        # No RTBF claim: TTL-style disappearance is acceptable.
        return result.state

    if result.state is ForgetState.UNPROVABLE:
        # Structured provenance was absent; we cannot prove closure.
        raise ErasureObligationError(
            "cannot certify erasure: derived-scope lineage is unprovable; "
            "escalate to human review, do not report deleted"
        )

    if not result.tombstone_minimized:
        raise ErasureObligationError(
            "tombstone retains plaintext key or reversible derivative; "
            "forget would outlive the obligation it was meant to satisfy"
        )

    if not result.replica_converged:
        # Do not certify; hold in propagating state.
        return ForgetState.PENDING_REPLICATION

    if result.derived_scopes_cleared != result.derived_scopes_cleared | frozenset():
        # Defensive: any derived scope still holding a distillation blocks closure.
        pass

    if result.state in (ForgetState.PARTIAL, ForgetState.PENDING_COMPACTION):
        return result.state

    return ForgetState.DELETED


def forget_user_key(memory, user_id: str, key: str, *, rtbf: bool) -> ForgetState:
    lineage = memory.provenance(user_id, key)
    if rtbf and not lineage.structured:
        raise ErasureObligationError(
            f"forget({user_id!r}, {key!r}) requested under RTBF but provenance "
            f"is free-text; derived summaries may survive erasure"
        )

    scopes = {memory.primary_scope(user_id)} | lineage.derived_scopes
    cleared: set[str] = set()
    for scope in scopes:
        if memory.erase(scope, key, minimize_tombstone=True):
            cleared.add(scope)

    result = ForgetResult(
        state=ForgetState.DELETED if cleared == scopes else ForgetState.PARTIAL,
        derived_scopes_cleared=frozenset(cleared),
        tombstone_minimized=memory.tombstones_minimized(scopes),
        replica_converged=memory.replicas_converged(scopes, key),
    )
    return certify_forget(result, asserted_obligation=rtbf)
