# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-prove-forgetting-before-it-may-re-read-a-redacted-memory-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-prove-forgetting-before-it-may-re-read-a-redacted-memory-scope.warrant.json
# Markdown SHA-256:   6f9fd76542cf0c5f9205d2b229388c7c6d13fec434107826ce4ea95228ec2f8d
# Code AST SHA-256:   a5bb49f0c400be97a4a3759db2a90def1ccb2c26cee521889237fe3fbce3ba87
# Verified Classes:   ErasureAttestationError, ForgetResult, ReadResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ErasureAttestationError(RuntimeError):
    """Raised when an instance attempts to attest erasure outside the condition of validity."""
    pass


@dataclass
class ForgetResult:
    scope: str
    generation: int
    unresolved_projections: list[str] = field(default_factory=list)


@dataclass
class ReadResult:
    scope: str
    generation: int
    projection: str
    contains_redacted: bool


def attest_erasure(
    forget: ForgetResult,
    reads: Iterable[ReadResult],
    declared_projections: set[str],
) -> dict:
    # Guardrail 1: tombstone-plus-drain contract requires an empty drain list.
    if forget.unresolved_projections:
        raise ErasureAttestationError(
            f"scope {forget.scope!r} has unresolved projections "
            f"{forget.unresolved_projections!r}; drain before attesting"
        )

    reads = list(reads)

    # Guardrail 2: every declared projection must have been read.
    read_projections = {r.projection for r in reads}
    missing = declared_projections - read_projections
    if missing:
        raise ErasureAttestationError(
            f"attestation for {forget.scope!r} omits projections {sorted(missing)!r}; "
            "tombstone success is not erasure success"
        )

    # Guardrail 3: no read may lag the forget generation (stale cache key).
    for r in reads:
        if r.generation < forget.generation:
            raise ErasureAttestationError(
                f"read of projection {r.projection!r} at generation {r.generation} "
                f"lags forget generation {forget.generation}; cache key must include generation"
            )
        if r.contains_redacted:
            raise ErasureAttestationError(
                f"projection {r.projection!r} still reconstructs redacted content "
                f"at generation {r.generation}"
            )

    return {
        "scope": forget.scope,
        "generation": forget.generation,
        "clean": True,
        "projections_read": sorted(read_projections),
        "inheritable": False,
    }
