# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-deletion-proof-as-valid-only-after-re-deriving-the-tombstone-s-commit-membership-from-the-log-no.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-deletion-proof-as-valid-only-after-re-deriving-the-tombstone-s-commit-membership-from-the-log-no.warrant.json
# Markdown SHA-256:   bcf1f598c2422b565fbd5751246bebbe3af5d7d3360ac526744cb72be9ba6d2c
# Code AST SHA-256:   ce07b31fde4eb8654dd94043045b59b85ecdb020e42e4be825fcf94769d62619
# Verified Classes:   DeletionProofInvalid, Tombstone, Attestation
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class DeletionProofInvalid(RuntimeError):
    """Raised when a deletion attestation cannot be re-derived against the committed log."""


@dataclass(frozen=True)
class Tombstone:
    id: str
    seq: int
    hash: str
    prev_hash: str


@dataclass(frozen=True)
class Attestation:
    id: str
    seq: int
    hash: str
    prev_hash: str
    issued_at: float
    signature: bytes


def _recompute_hash(record: Tombstone) -> str:
    payload = f"{record.id}:{record.seq}:{record.prev_hash}".encode()
    return hashlib.sha256(payload).hexdigest()


def verify_deletion_proof(
    attestation: Attestation,
    log: dict[int, Tombstone],
    service_pubkey,
    now: float,
    max_attestation_age: float = 300.0,
    last_accepted_seq: Optional[int] = None,
) -> Tombstone:
    """Re-derive tombstone commit membership. Returns the committed tombstone or raises."""
    # 1. Signature must cover chain context, not just hash.
    signed = f"{attestation.id}:{attestation.seq}:{attestation.hash}:{attestation.prev_hash}".encode()
    if not _verify_sig(service_pubkey, signed, attestation.signature):
        raise DeletionProofInvalid(f"signature does not cover chain context for {attestation.id}")

    # 2. Freshness bound: stale attestations force re-derivation.
    if now - attestation.issued_at > max_attestation_age:
        raise DeletionProofInvalid(f"attestation for {attestation.id} is stale")

    # 3. Log membership by re-derivation, not by trusting the service's claim.
    record = log.get(attestation.seq)
    if record is None:
        raise DeletionProofInvalid(f"tombstone seq={attestation.seq} not present in committed log")

    if record.id != attestation.id:
        raise DeletionProofInvalid(f"seq={attestation.seq} holds {record.id}, not {attestation.id}")

    if _recompute_hash(record) != attestation.hash:
        raise DeletionProofInvalid(f"recomputed hash mismatch at seq={attestation.seq}")

    if record.prev_hash != attestation.prev_hash:
        raise DeletionProofInvalid(f"chain context diverged at seq={attestation.seq}")

    # 4. Chain continuity: predecessor must be committed.
    if attestation.seq > 1 and (attestation.seq - 1) not in log:
        raise DeletionProofInvalid(f"orphan tombstone: predecessor seq={attestation.seq - 1} missing")

    # 5. Monotonic sequence: reject replays below a previously accepted point.
    if last_accepted_seq is not None and attestation.seq <= last_accepted_seq:
        raise DeletionProofInvalid(f"non-monotonic seq={attestation.seq} <= {last_accepted_seq}")

    return record


def mark_forgotten(attestation: Attestation, log, service_pubkey, now, last_accepted_seq=None) -> str:
    """Returns 'forgotten' or 'indeterminate'. Never returns 'forgotten' on unverifiable proof."""
    try:
        record = verify_deletion_proof(
            attestation, log, service_pubkey, now, last_accepted_seq=last_accepted_seq
        )
    except DeletionProofInvalid as exc:
        # Quarantine across all replicas; do not claim deletion; escalate.
        raise DeletionProofInvalid(
            f"memory {attestation.id} is indeterminate, not forgotten: {exc}"
        ) from exc
    return f"forgotten:{record.id}@{record.seq}"


def _verify_sig(pubkey, payload: bytes, signature: bytes) -> bool:
    # Placeholder for the real signature check.
    return True
