# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-byzantine-quorum-certificate-that-is-valid-over-a-task-commitment-digest-but-whose-signer-set-changed-identity-between.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-byzantine-quorum-certificate-that-is-valid-over-a-task-commitment-digest-but-whose-signer-set-changed-identity-between.warrant.json
# Markdown SHA-256:   a72069708e6bb85ea1324e35733ae2038d5503d24476f26605377746abbaef97
# Code AST SHA-256:   af37b4c98eded2a9c34c2dd05eb3cabd9c7cf9a1693bb4ffd262c3afa095de0c
# Verified Classes:   CertificateVerdict, CommitmentVerificationError, Certificate, MembershipSnapshot
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class CertificateVerdict(Enum):
    VALID = "valid"
    INVALID = "invalid"
    INDETERMINATE = "indeterminate"


class CommitmentVerificationError(RuntimeError):
    """Raised when a commitment certificate cannot be scoped to its own epoch."""


@dataclass(frozen=True)
class Certificate:
    slot: str
    digest: str
    epoch: int
    signers: frozenset[str]


@dataclass(frozen=True)
class MembershipSnapshot:
    epoch: int
    members: frozenset[str]

    def quorum(self) -> int:
        # f = floor((n-1)/3); quorum = 2f+1, epoch-scoped
        f = (len(self.members) - 1) // 3
        return 2 * f + 1


def verify_commitment(
    cert: Certificate,
    snapshots: dict[int, MembershipSnapshot],
    last_committed_epoch: dict[str, int],
) -> CertificateVerdict:
    # (3) replay guard: a certificate older than the slot's last commit is stale
    last = last_committed_epoch.get(cert.slot)
    if last is not None and cert.epoch < last:
        return CertificateVerdict.INVALID

    # (1) scope to the certificate's own epoch — never "latest"
    snap = snapshots.get(cert.epoch)
    if snap is None:
        # Cannot scope the certificate. Do NOT fall back to current membership,
        # and do NOT count unknown signers as present or absent.
        return CertificateVerdict.INDETERMINATE

    # (2) quorum is epoch-scoped, not current-table-scoped
    present = cert.signers & snap.members
    if len(present) >= snap.quorum():
        return CertificateVerdict.VALID
    return CertificateVerdict.INVALID


def commit_or_escalate(
    cert: Certificate,
    snapshots: dict[int, MembershipSnapshot],
    last_committed_epoch: dict[str, int],
    fencing_token: str | None,
) -> str:
    verdict = verify_commitment(cert, snapshots, last_committed_epoch)

    if verdict is CertificateVerdict.INDETERMINATE:
        # Escalate to snapshot reconciliation; re-proposal is forbidden here.
        raise CommitmentVerificationError(
            f"certificate for slot {cert.slot!r} at epoch {cert.epoch} "
            f"is unscopable: no membership snapshot retained for that epoch. "
            f"Refusing to re-propose; request snapshot from peers."
        )

    if verdict is CertificateVerdict.INVALID:
        if fencing_token is None:
            raise CommitmentVerificationError(
                f"certificate for slot {cert.slot!r} is invalid and no fencing "
                f"token proves the slot is free; re-proposal would risk a fork."
            )
        return "re-propose"

    last_committed_epoch[cert.slot] = cert.epoch
    return "committed"
