# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-keeps-signing-with-a-rotated-out-key-after-a-cross-domain-revocation-notice-arrives-out-of-band.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-keeps-signing-with-a-rotated-out-key-after-a-cross-domain-revocation-notice-arrives-out-of-band.warrant.json
# Markdown SHA-256:   64cda25c5b36d111cfc8f45987e8796a769a636a2be939c76041cf0a9f0fa040
# Code AST SHA-256:   495637772f1f44acfe55a7afc0cb3288905f144dd1b8532309042475c2add6c5
# Verified Classes:   EpochMismatchError, Warrant, TransparencyEntry, MonotonicKeyLog
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EpochMismatchError(RuntimeError):
    """Raised when a warrant's epoch cannot be reconciled with the verifier's
    monotonic view of the issuer's key-transparency log."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    issuer_epoch: int
    not_after_epoch: int
    key_id: str
    payload_hash: str
    signature: bytes


@dataclass(frozen=True)
class TransparencyEntry:
    issuer: str
    epoch: int
    key_id: str
    prev_hash: str
    entry_hash: str


class MonotonicKeyLog:
    """Append-only, hash-chained view of an issuer's key epochs.
    A verifier may only advance forward; gaps are buffered, never applied."""

    def __init__(self) -> None:
        self._entries: dict[str, list[TransparencyEntry]] = {}
        self._pending: dict[str, dict[int, TransparencyEntry]] = {}

    def ingest(self, entry: TransparencyEntry) -> None:
        chain = self._entries.setdefault(entry.issuer, [])
        # Buffer out-of-order entries; apply only when the chain is contiguous.
        self._pending.setdefault(entry.issuer, {})[entry.epoch] = entry
        while True:
            pending = self._pending[entry.issuer]
            next_epoch = len(chain) + 1
            if next_epoch not in pending:
                break
            nxt = pending.pop(next_epoch)
            expected_prev = chain[-1].entry_hash if chain else "GENESIS"
            if nxt.prev_hash != expected_prev:
                raise EpochMismatchError(
                    f"hash-chain break for {entry.issuer} at epoch {nxt.epoch}: "
                    f"expected prev {expected_prev}, got {nxt.prev_hash}"
                )
            chain.append(nxt)

    def known_epoch(self, issuer: str) -> int:
        return len(self._entries.get(issuer, []))

    def key_for_epoch(self, issuer: str, epoch: int) -> str:
        chain = self._entries.get(issuer, [])
        if epoch < 1 or epoch > len(chain):
            raise EpochMismatchError(
                f"epoch {epoch} for {issuer} not yet confirmed in local log "
                f"(known up to {len(chain)})"
            )
        return chain[epoch - 1].key_id


def verify_warrant(
    w: Warrant,
    log: MonotonicKeyLog,
    *,
    allow_provisional: bool,
) -> str:
    """Returns 'final' or 'provisional'. Provisional warrants may be routed
    but MUST NOT gate irreversible side effects."""
    known = log.known_epoch(w.issuer)
    if known < w.issuer_epoch:
        if not allow_provisional:
            raise EpochMismatchError(
                f"warrant from {w.issuer} at epoch {w.issuer_epoch} exceeds "
                f"local log ({known}); refusing final verification"
            )
        return "provisional"
    if w.issuer_epoch > w.not_after_epoch:
        raise EpochMismatchError(
            f"warrant epoch {w.issuer_epoch} past not_after {w.not_after_epoch}"
        )
    committed_key = log.key_for_epoch(w.issuer, w.issuer_epoch)
    if committed_key != w.key_id:
        raise EpochMismatchError(
            f"warrant signed by {w.key_id} but epoch {w.issuer_epoch} of "
            f"{w.issuer} commits to {committed_key}"
        )
    return "final"


def commit_side_effect(w: Warrant, log: MonotonicKeyLog) -> None:
    """Intermediate hop: irreversible commit is gated on FINAL verification."""
    status = verify_warrant(w, log, allow_provisional=False)
    if status != "final":
        # Defensive: verify_warrant already raises, but keep the invariant explicit.
        raise EpochMismatchError(
            f"refusing irreversible commit under {status} warrant from {w.issuer}"
        )
    # ... perform the commit ...
