# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-s-vote-be-rejected-when-its-plan-commitment-quorum-certificate-is-internally-consistent-but-references-a-superseded-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-s-vote-be-rejected-when-its-plan-commitment-quorum-certificate-is-internally-consistent-but-references-a-superseded-epoch.warrant.json
# Markdown SHA-256:   d814b4c1848a0360baa6319308a913e12d6aec062dce45d10142e3806b6638ac
# Code AST SHA-256:   397c68a07212cddecdd3b8d0ce6a6a75f726521f2324c50b8383e3aadaa72ddc
# Verified Classes:   StaleQuorumEpoch, QuorumCertificate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleQuorumEpoch(RuntimeError):
    """Raised when a quorum certificate's signed epoch does not match the
    verifier's current epoch, or when the QC's epoch is not inside the
    signed message domain (making replay across rotations undetectable)."""
    pass


@dataclass(frozen=True)
class QuorumCertificate:
    plan_digest: bytes
    epoch: int
    signers: frozenset[str]
    signatures: tuple[bytes, ...]
    signed_message: bytes  # MUST be H(plan_digest || epoch), not H(plan_digest)


def verify_qc_for_admission(
    qc: QuorumCertificate,
    current_epoch: int,
    authorized_keys: frozenset[str],
    threshold: int,
) -> None:
    # Invariant 1: epoch must be inside the signed domain.
    expected_msg = hashlib.sha256(
        qc.plan_digest + qc.epoch.to_bytes(8, "big")
    ).digest()
    if qc.signed_message != expected_msg:
        raise StaleQuorumEpoch(
            f"QC signed domain does not bind epoch {qc.epoch}; "
            f"replay across rotations is undetectable"
        )

    # Invariant 2: strict epoch equality, no grace window.
    if qc.epoch != current_epoch:
        direction = "stale" if qc.epoch < current_epoch else "future"
        raise StaleQuorumEpoch(
            f"{direction} QC: signed epoch {qc.epoch} != current {current_epoch}"
        )

    # Invariant 3: threshold over distinct authorized signers.
    distinct = qc.signers & authorized_keys
    if len(distinct) < threshold:
        raise StaleQuorumEpoch(
            f"insufficient authorized signers: {len(distinct)} < {threshold}"
        )


def admit_plan_resume(
    qc: QuorumCertificate,
    current_epoch: int,
    authorized_keys: frozenset[str],
    threshold: int,
) -> str:
    verify_qc_for_admission(qc, current_epoch, authorized_keys, threshold)
    return "ADMITTED"
