# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-halt-delegation-when-a-revocation-epoch-advances-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-halt-delegation-when-a-revocation-epoch-advances-mid-chain.warrant.json
# Markdown SHA-256:   37d204222b26f7674cab3b0282f404616d92c0a47dd2de571c4ec3135ee58393
# Code AST SHA-256:   b1a13d11cfb2be0bae3199048bca69966e1f33aeb0e1a8fdb8d0a2fcdcea5970
# Verified Classes:   StaleEpochDelegationError, RevokedAncestorError, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleEpochDelegationError(RuntimeError):
    """Raised when a warrant is minted or consumed at an epoch that has been superseded."""


class RevokedAncestorError(RuntimeError):
    """Raised when an ancestor warrant hash appears in the current revocation set."""


@dataclass(frozen=True)
class Warrant:
    scope: str
    epoch: int
    parent_hash: str | None
    warrant_hash: str


def _hash(scope: str, epoch: int, parent_hash: str | None) -> str:
    return hashlib.sha256(f"{scope}|{epoch}|{parent_hash}".encode()).hexdigest()


def mint_child(
    parent: Warrant,
    child_scope: str,
    root_epoch: int,
    revoked_hashes: frozenset[str],
) -> Warrant:
    # Hard stop: an ancestor (or self) was explicitly revoked.
    if parent.warrant_hash in revoked_hashes or parent.parent_hash in revoked_hashes:
        raise RevokedAncestorError(
            f"parent {parent.warrant_hash[:12]} is in revocation set; halt chain"
        )

    # Epoch advanced but this subtree was not the revocation target.
    # Minting at the stale epoch would produce a born-dead child.
    if root_epoch > parent.epoch:
        raise StaleEpochDelegationError(
            f"parent epoch {parent.epoch} < root epoch {root_epoch}; "
            f"re-derive parent warrant before minting child"
        )

    if root_epoch < parent.epoch:
        # Parent claims a future epoch: epoch laundering attempt.
        raise StaleEpochDelegationError(
            f"parent epoch {parent.epoch} > root epoch {root_epoch}; reject"
        )

    child_hash = _hash(child_scope, parent.epoch, parent.warrant_hash)
    return Warrant(
        scope=child_scope,
        epoch=parent.epoch,
        parent_hash=parent.warrant_hash,
        warrant_hash=child_hash,
    )


def consume(w: Warrant, root_epoch: int, revoked_hashes: frozenset[str]) -> None:
    if w.warrant_hash in revoked_hashes or w.parent_hash in revoked_hashes:
        raise RevokedAncestorError(f"warrant {w.warrant_hash[:12]} revoked at consumption")
    if w.epoch != root_epoch:
        raise StaleEpochDelegationError(
            f"warrant epoch {w.epoch} != root epoch {root_epoch}; re-validate before use"
        )
