# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-scoped-forget-request-that-would-orphan-a-dependent-memory-edge.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-scoped-forget-request-that-would-orphan-a-dependent-memory-edge.warrant.json
# Markdown SHA-256:   dca517943d9e34d9fe6250393add8d40e0ad2707ceca8150bdc9d12981443889
# Code AST SHA-256:   0627e0689a3d05fae9545a26c0064201aed188dba2122877ce232d526c02cd03
# Verified Classes:   RetentionClass, ForgetRefused, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class RetentionClass(Enum):
    EPHEMERAL = 1
    STANDARD = 2
    LEGAL_HOLD = 3


class ForgetRefused(RuntimeError):
    """Raised when a scoped forget would orphan a dependent memory edge
    that cannot be atomically reconciled within the forget's closure."""

    def __init__(self, orphans: list[str], blocking_class: RetentionClass):
        self.orphans = orphans
        self.blocking_class = blocking_class
        super().__init__(
            f"forget refused: {len(orphans)} orphaned dependents "
            f"under {blocking_class.name}: {orphans}"
        )


@dataclass
class MemoryRecord:
    id: str
    retention: RetentionClass
    derived_from: list[str] = field(default_factory=list)
    tombstoned: bool = False


def scoped_forget(
    store: dict[str, MemoryRecord],
    target_ids: list[str],
    closure_scope: set[str],
    cascade: bool,
) -> dict[str, int]:
    # 1. Compute the full dependent closure of the target set.
    dependents: list[MemoryRecord] = [
        r for r in store.values()
        if any(p in target_ids for p in r.derived_from) and r.id not in target_ids
    ]

    # 2. Any dependent outside the declared scope widens the closure or refuses.
    external = [r for r in dependents if r.id not in closure_scope]
    if external and not cascade:
        raise ForgetRefused([r.id for r in external], RetentionClass.STANDARD)

    # 3. A dependent under a stricter class than the parent blocks cascade.
    for r in dependents:
        if r.retention.value > max(
            store[t].retention.value for t in target_ids if t in store
        ):
            raise ForgetRefused([r.id for r in dependents], r.retention)

    # 4. Atomic transition: tombstone dependents, then redact targets.
    #    If any step fails, the caller must roll back — modelled here by
    #    validating the whole set before mutating.
    for r in dependents:
        if r.tombstoned:
            continue
        if r.retention is RetentionClass.LEGAL_HOLD:
            raise ForgetRefused([r.id for r in dependents], RetentionClass.LEGAL_HOLD)

    for r in dependents:
        r.tombstoned = True
    for tid in target_ids:
        store.pop(tid, None)

    return {"forgotten": len(target_ids), "tombstoned": len(dependents)}
