# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-forget-call-it-cannot-prove-was-honored-tombstone-evidence-divergence-in-scoped-memory-tools.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-forget-call-it-cannot-prove-was-honored-tombstone-evidence-divergence-in-scoped-memory-tools.warrant.json
# Markdown SHA-256:   fa8802325388f0aab02f2c5005c4fd552cd26bf4911dacd4a42fd3a45f7b0d36
# Code AST SHA-256:   3ba9a222376cd04a7ea61437c403a3b3a91d509e80f863139979ec62edb16dba
# Verified Classes:   ErasureAttestationError, RetentionFloorBlocked, ScopeEvidence, ErasureEvidence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Callable


class ErasureAttestationError(RuntimeError):
    """Raised when an agent attempts to attest erasure without read-verified
    tombstone coverage at every reachable scope."""


class RetentionFloorBlocked(ErasureAttestationError):
    """Raised when a forget is silently no-op'd by a scope's min_residency_s."""


@dataclass
class ScopeEvidence:
    scope: str
    tombstoned: bool
    eligible_at: float | None = None   # set when floor-blocked
    reason: str = ""


@dataclass
class ErasureEvidence:
    record_id: str
    scopes: list[ScopeEvidence] = field(default_factory=list)

    @property
    def uncovered_scopes(self) -> list[ScopeEvidence]:
        return [s for s in self.scopes if not s.tombstoned]


def forget_and_verify(
    record_id: str,
    reachable_scopes: list[str],
    forget: Callable[[str, str], dict],
    read: Callable[[str], dict],
    now: Callable[[], float] = time.time,
) -> ErasureEvidence:
    """Two-phase forget: issue tombstones, wait out the max propagation
    deadline, then re-read every scope. Returns evidence; never attests."""
    deadlines_ms: list[int] = []
    for scope in reachable_scopes:
        ack = forget(record_id, scope)
        # An 'ok' ack is a promise, not proof. Capture the deadline.
        if ack.get("status") != "ok":
            raise ErasureAttestationError(
                f"forget rejected for {record_id}@{scope}: {ack}"
            )
        deadlines_ms.append(int(ack.get("propagation_deadline_ms", 0)))

    # Wait for the slowest scope to propagate before reading back.
    time.sleep(max(deadlines_ms) / 1000.0)

    evidence = ErasureEvidence(record_id=record_id)
    for scope in reachable_scopes:
        state = read(scope)
        if state.get("status") == "tombstoned":
            evidence.scopes.append(ScopeEvidence(scope, tombstoned=True))
            continue
        # Content survived the forget: either floor-blocked or unpropagated.
        floor = state.get("retention_policy", {}).get("min_residency_s")
        if floor is not None and state.get("written_at") is not None:
            eligible_at = float(state["written_at"]) + float(floor)
            if now() < eligible_at:
                evidence.scopes.append(
                    ScopeEvidence(
                        scope,
                        tombstoned=False,
                        eligible_at=eligible_at,
                        reason="retention_floor",
                    )
                )
                continue
        evidence.scopes.append(
            ScopeEvidence(scope, tombstoned=False, reason="unpropagated_or_orphan")
        )
    return evidence


def attest_erasure(evidence: ErasureEvidence) -> str:
    """Sign an erasure report only with full read-verified coverage."""
    uncovered = evidence.uncovered_scopes
    if uncovered:
        detail = "; ".join(
            f"{s.scope}: {s.reason}"
            + (f" (eligible_at={s.eligible_at:.0f})" if s.eligible_at else "")
            for s in uncovered
        )
        raise ErasureAttestationError(
            f"cannot attest erasure of {evidence.record_id}: "
            f"uncovered scopes [{detail}]. Emit a conditional report instead."
        )
    return f"erased:{evidence.record_id}:scopes={len(evidence.scopes)}"


def attest_or_report(evidence: ErasureEvidence) -> dict:
    """Operational wrapper: refuse to lie, degrade to a conditional report."""
    try:
        return {"attestation": attest_erasure(evidence), "conditional": False}
    except ErasureAttestationError as exc:
        return {
            "attestation": None,
            "conditional": True,
            "detail": str(exc),
            "uncovered": [
                {"scope": s.scope, "reason": s.reason, "eligible_at": s.eligible_at}
                for s in evidence.uncovered_scopes
            ],
        }
