# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-sign-a-commit-certificate-when-its-own-equivocation-evidence-is-younger-than-the-quorum-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-sign-a-commit-certificate-when-its-own-equivocation-evidence-is-younger-than-the-quorum-epoch.warrant.json
# Markdown SHA-256:   a6d3a318e113ed690fbe00aa10d4ab107360ad454c1c86e154aeb7280936b0bf
# Code AST SHA-256:   7aabf325ad1b18aca526d8c3011308b6e08cd1fd652780ab6d18e8948f4f77c6
# Verified Classes:   EvidenceTooYoungToVeto, EquivocationEvidence, CommitCertificate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class EvidenceTooYoungToVeto(RuntimeError):
    """Raised when a validator attempts to veto a certificate using
    equivocation evidence whose epoch postdates the certificate's
    signature-collection epoch."""
    pass


@dataclass(frozen=True)
class EquivocationEvidence:
    signer_id: str
    witnessed_epoch: int
    evidence_hash: str


@dataclass(frozen=True)
class CommitCertificate:
    task_batch: str
    collection_epoch: int
    signers: tuple


def evaluate_signature(
    cert: CommitCertificate,
    self_id: str,
    evidence: Optional[EquivocationEvidence],
) -> dict:
    """Decide whether to sign, veto, or sign-with-annotation.

    Invariant: veto is permitted only when evidence.witnessed_epoch
    <= cert.collection_epoch. Younger evidence must not veto, or the
    validator becomes a liveness fault.
    """
    if evidence is None:
        return {"action": "sign", "annotation": None}

    if evidence.witnessed_epoch <= cert.collection_epoch:
        return {"action": "veto", "annotation": None}

    # Evidence is younger than the collection epoch: signing is mandatory.
    # But we must not silently swallow it -- annotate for retrospective slashing.
    if evidence.witnessed_epoch > cert.collection_epoch:
        return {
            "action": "sign",
            "annotation": {
                "pending_equivocation": evidence.evidence_hash,
                "witnessed_epoch": evidence.witnessed_epoch,
                "deferred_until_epoch": evidence.witnessed_epoch + 1,
            },
        }

    # Unreachable given the comparisons above, but made explicit so that a
    # future refactor cannot quietly widen the veto window.
    raise EvidenceTooYoungToVeto(
        f"validator {self_id} reached an undefined evidence epoch comparison "
        f"for certificate {cert.task_batch}: ev={evidence.witnessed_epoch} "
        f"cert={cert.collection_epoch}"
    )
