# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-acknowledges-a-scoped-forget-call-before-the-retention-ledger-has-confirmed-deletion-across-all-replicas.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-acknowledges-a-scoped-forget-call-before-the-retention-ledger-has-confirmed-deletion-across-all-replicas.warrant.json
# Markdown SHA-256:   6f3493ae9faa45881b7e6b3c3204411853b77851a1e74817e54c2d6b44defe69
# Code AST SHA-256:   ef55c1c258f0604691c43bb27d1e1ec6f92c75005ea5f98e82fa180a1370055b
# Verified Classes:   DeletionUnverified, ForgetProof
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class DeletionUnverified(RuntimeError):
    """Raised when an agent treats a bare forget-ack as compliance-grade deletion."""


@dataclass(frozen=True)
class ForgetProof:
    scope: str
    key: str
    epoch: int
    min_replica_epoch: int
    signature: str


def _sign(scope: str, key: str, epoch: int, min_replica_epoch: int) -> str:
    payload = f"{scope}|{key}|{epoch}|{min_replica_epoch}".encode()
    return hashlib.sha256(payload).hexdigest()


def issue_forget(scope: str, key: str, epoch: int, min_replica_epoch: int) -> dict:
    # Substrate-side: only returns a proof once tombstones + derived-cache
    # invalidation have converged to at least min_replica_epoch.
    return {
        "status": "deleted",
        "proof": ForgetProof(
            scope=scope,
            key=key,
            epoch=epoch,
            min_replica_epoch=min_replica_epoch,
            signature=_sign(scope, key, epoch, min_replica_epoch),
        ),
    }


def require_compliance_forget(response: dict, scope: str, key: str, expected_epoch: int) -> ForgetProof:
    """Agent-side guard: refuse to mark a key compliance-forgotten on a bare 'ok'."""
    if response.get("status") != "deleted":
        raise DeletionUnverified(
            f"forget({scope},{key}) returned status={response.get('status')!r}; "
            "not a proof-bearing acknowledgement"
        )
    proof = response.get("proof")
    if not isinstance(proof, ForgetProof):
        raise DeletionUnverified(
            f"forget({scope},{key}) returned 'ok' without a bound proof token; "
            "epistemic forgetting only — do not assert deletion downstream"
        )
    if proof.epoch != expected_epoch:
        raise DeletionUnverified(
            f"proof epoch {proof.epoch} != write epoch {expected_epoch}; "
            "tombstone may not cover the written value"
        )
    if proof.min_replica_epoch < expected_epoch:
        raise DeletionUnverified(
            f"min_replica_epoch {proof.min_replica_epoch} < required {expected_epoch}; "
            "peer auditors may still read the key"
        )
    expected_sig = _sign(proof.scope, proof.key, proof.epoch, proof.min_replica_epoch)
    if proof.signature != expected_sig:
        raise DeletionUnverified(f"proof signature mismatch for {scope}/{key}")
    return proof


def close_task(trace: list[dict], scope: str, key: str, write_epoch: int) -> None:
    """Task completion path: every forget in the trace must carry a proof."""
    forgets = [r for r in trace if r.get("op") == "forget"]
    if not forgets:
        raise DeletionUnverified(f"no forget recorded for {scope}/{key}")
    for r in forgets:
        require_compliance_forget(r["response"], scope, key, write_epoch)
    # Only now is it safe to emit a completion record asserting deletion.
    return None
