# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-forget-acknowledgement-as-a-tombstone-rather-than-a-deletion-and-why-the-distinction-is-the-only-thing-preventing-scoped.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-forget-acknowledgement-as-a-tombstone-rather-than-a-deletion-and-why-the-distinction-is-the-only-thing-preventing-scoped.warrant.json
# Markdown SHA-256:   6914f283f0ff6182d02251a848d3f58ea2cf5b2161bf67177abe886ab1b08021
# Code AST SHA-256:   cf08ce7bcc26503f9598e7d07c03be9fa9b6e69704f8dc2bcc7a1e99437405d5
# Verified Classes:   ResurrectionRiskError, ForgetAcknowledgementError, ForgetAck, QuarantineSpan, InstanceMemoryGuard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Optional


class ResurrectionRiskError(RuntimeError):
    """Raised when a write would re-emit content under an active tombstone."""
    pass


class ForgetAcknowledgementError(RuntimeError):
    """Raised when a forget ack is treated as deletion but is only a tombstone."""
    pass


@dataclass
class ForgetAck:
    scope: str
    key: str
    tombstone_id: Optional[str]
    reclaim_after: Optional[datetime]
    deleted_at: Optional[datetime]

    @property
    def is_deletion(self) -> bool:
        # Deletion requires proof of physical erasure under strong consistency.
        return self.deleted_at is not None and self.tombstone_id is None

    @property
    def is_tombstone(self) -> bool:
        return not self.is_deletion


@dataclass
class QuarantineSpan:
    content_hash: str
    scope: str
    key: str
    until: datetime


@dataclass
class InstanceMemoryGuard:
    quarantined: list = field(default_factory=list)

    def on_forget(self, ack: ForgetAck, content: str) -> None:
        if ack.is_tombstone:
            if ack.reclaim_after is None:
                raise ForgetAcknowledgementError(
                    f"tombstone ack for {ack.scope}/{ack.key} lacks reclaim_after; "
                    "cannot bound quarantine window"
                )
            self.quarantined.append(QuarantineSpan(
                content_hash=hashlib.sha256(content.encode()).hexdigest(),
                scope=ack.scope,
                key=ack.key,
                until=ack.reclaim_after,
            ))
        # deletion: nothing to quarantine, content is physically gone

    def check_write(self, scope: str, key: str, payload: str, now: datetime) -> None:
        h = hashlib.sha256(payload.encode()).hexdigest()
        for span in self.quarantined:
            if now < span.until and span.content_hash in h:
                raise ResurrectionRiskError(
                    f"write to {scope}/{key} would resurrect content tombstoned "
                    f"under {span.scope}/{span.key} until {span.until.isoformat()}"
                )
            if now < span.until and h == span.content_hash:
                raise ResurrectionRiskError(
                    f"exact-content resurrection into {scope}/{key}"
                )

    def confirm_to_user(self, ack: ForgetAck, now: datetime, strong_read_not_found: bool) -> str:
        if ack.is_tombstone:
            if ack.reclaim_after and now < ack.reclaim_after:
                raise ForgetAcknowledgementError(
                    "cannot confirm erasure before reclaim_after; "
                    "operation is a tombstone, not a deletion"
                )
            if not strong_read_not_found:
                raise ForgetAcknowledgementError(
                    "strong-consistency read did not confirm NOT_FOUND; "
                    "physical row may persist"
                )
        return "erased"
