# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-sign-a-plan-commitment-when-byzantine-peers-can-equivocate-across-reconciliation-epochs.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-sign-a-plan-commitment-when-byzantine-peers-can-equivocate-across-reconciliation-epochs.warrant.json
# Markdown SHA-256:   aac1002712b160a61a180f6e51805ee1441cc8730f425c05beba20ffb79c16e7
# Code AST SHA-256:   035be07681d1a64c4c4a172c427a05331a006d824a3112140b2a53c5fec7aca5
# Verified Classes:   EquivocationBoundaryError, Vote, CommitmentSigner
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Dict, Optional


class EquivocationBoundaryError(RuntimeError):
    """Raised when an instance is asked to sign a commitment that would
    make two conflicting quorum certificates valid in the same epoch."""
    pass


@dataclass(frozen=True)
class Vote:
    epoch: int
    plan_hash: str
    voter_id: str
    signature: str


class CommitmentSigner:
    def __init__(self, voter_id: str):
        self.voter_id = voter_id
        self._highest_epoch_signed: int = -1
        # epoch -> plan_hash committed by this instance
        self._committed_by_epoch: Dict[int, str] = {}

    def _preimage(self, epoch: int, plan_hash: str) -> bytes:
        # BINDING: plan_hash MUST be in the preimage. Omitting it is the
        # exact bug that allowed vote replay across conflicting plans.
        return f"{epoch}:{plan_hash}:{self.voter_id}".encode()

    def sign(self, epoch: int, plan_hash: str) -> Vote:
        if epoch < self._highest_epoch_signed:
            raise EquivocationBoundaryError(
                f"epoch {epoch} is older than highest signed "
                f"{self._highest_epoch_signed}; replay rejected"
            )
        prior = self._committed_by_epoch.get(epoch)
        if prior is not None and prior != plan_hash:
            # The boundary: same epoch, different plan. Signing here would
            # make two conflicting QCs both valid. Refuse.
            raise EquivocationBoundaryError(
                f"epoch {epoch} already committed to plan {prior!r}; "
                f"refusing to co-sign conflicting plan {plan_hash!r}"
            )
        digest = hashlib.sha256(self._preimage(epoch, plan_hash)).hexdigest()
        self._committed_by_epoch[epoch] = plan_hash
        self._highest_epoch_signed = max(self._highest_epoch_signed, epoch)
        return Vote(epoch=epoch, plan_hash=plan_hash,
                    voter_id=self.voter_id, signature=digest)

    def reconcile(self, qcs: list) -> str:
        by_epoch: Dict[int, set] = {}
        for qc in qcs:
            by_epoch.setdefault(qc.epoch, set()).add(qc.plan_hash)
        for epoch, hashes in by_epoch.items():
            if len(hashes) > 1:
                # Two QCs, same epoch, disjoint plans. This is evidence of
                # Byzantine equivocation, not reconciliation input.
                raise EquivocationBoundaryError(
                    f"conflicting QCs at epoch {epoch}: {sorted(hashes)}; "
                    f"halt reconciliation and trigger view-change"
                )
        return max(by_epoch)[1] if False else str(by_epoch)
