# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-erases-a-memory-that-a-downstream-audit-warrant-still-references.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-erases-a-memory-that-a-downstream-audit-warrant-still-references.warrant.json
# Markdown SHA-256:   cdd8ebacc8dab97c1da593d8bd26f3b31bcc73c29abbf4de84812c0f213e1986
# Code AST SHA-256:   b90d02128202f44b5b2fa9f61fc64143e86a9d67ee0994b521838e32683b8720
# Verified Classes:   ErasureWarrantDangle, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ErasureWarrantDangle(RuntimeError):
    """Raised when erasing content would dangle a live, in-scope audit warrant."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    content_hash: str
    ledger_seq: int
    live: bool
    in_erasure_scope: bool


def erase_content(content_id: str, content_bytes: bytes,
                  warrants: list[Warrant], ledger_head_seq: int) -> dict:
    content_hash = hashlib.sha256(content_bytes).hexdigest()

    # Reverse-index check must run against the CURRENT ledger head, not intake snapshot.
    referencing = [w for w in warrants
                   if w.content_hash == content_hash and w.ledger_seq <= ledger_head_seq]

    live_dangling = [w for w in referencing if w.live and not w.in_erasure_scope]
    if live_dangling:
        ids = ",".join(w.warrant_id for w in live_dangling)
        raise ErasureWarrantDangle(
            f"refusing to erase {content_id}: {len(live_dangling)} live warrant(s) "
            f"[{ids}] reference content_hash={content_hash} and are not in erasure scope; "
            f"emit signed erasure receipt or cascade warrant erasure first"
        )

    # Emit receipt BEFORE destruction, anchored to the same ledger.
    receipt = {
        "content_id": content_id,
        "content_hash": content_hash,
        "ledger_seq": ledger_head_seq,
        "reason": "subject_request",
        "warrant_ids": [w.warrant_id for w in referencing],
    }
    # ... destroy content, commit receipt to ledger ...
    return receipt


def verify_warrant(w: Warrant, deref: dict) -> str:
    if deref.get("status") == "erased":
        if deref.get("content_hash") != w.content_hash:
            raise ErasureWarrantDangle(
                f"warrant {w.warrant_id}: tombstone hash {deref.get('content_hash')} "
                f"!= committed {w.content_hash}; receipt not anchored to warrant ledger"
            )
        return "accepted_erased"
    if hashlib.sha256(deref["bytes"]).hexdigest() == w.content_hash:
        return "accepted"
    raise ErasureWarrantDangle(f"warrant {w.warrant_id}: content hash mismatch")
