# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-plan-commitment-in-a-byzantine-quorum-when-peer-agents-sign-conflicting-sub-goal-manifests.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-plan-commitment-in-a-byzantine-quorum-when-peer-agents-sign-conflicting-sub-goal-manifests.warrant.json
# Markdown SHA-256:   70d4ec93ab33305bcd0b29c62bfcdd757c382cfb0f708573c28bd05f54acbbc6
# Code AST SHA-256:   fefa6b67407c7421622b8bb288e2e4b383ba32dd992c2ae21cf25cee012a1a9e
# Verified Classes:   EquivocationDetected, IncompleteCertificate, VoteRecord
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Dict, List, Tuple


class EquivocationDetected(RuntimeError):
    """Raised when a signer contributes to two distinct plan-hash preimages in one round."""
    pass


class IncompleteCertificate(RuntimeError):
    """Raised when a commit certificate lacks raw vote records for preimage recomputation."""
    pass


@dataclass(frozen=True)
class VoteRecord:
    signer: str
    round: int
    plan_hash: str
    recipient_set: Tuple[str, ...]
    prev_cert_hash: str
    signature: str  # in production: asymmetric sig over the preimage below

    def preimage(self) -> str:
        return f"{self.round}|{self.plan_hash}|{','.join(sorted(self.recipient_set))}|{self.prev_cert_hash}"

    def recompute(self) -> str:
        return hashlib.sha256(self.preimage().encode()).hexdigest()


def verify_and_commit(
    round_no: int,
    claimed_plan_hash: str,
    records: List[VoteRecord],
    quorum: int,
) -> str:
    if len(records) < quorum:
        raise IncompleteCertificate(
            f"round {round_no}: only {len(records)} records, need {quorum}"
        )

    seen: Dict[str, Dict[str, VoteRecord]] = {}
    for rec in records:
        if rec.round != round_no:
            raise IncompleteCertificate(
                f"round mismatch: record says {rec.round}, expected {round_no}"
            )
        if rec.recompute() != rec.signature:
            raise IncompleteCertificate(
                f"signer {rec.signer}: preimage does not match signature"
            )
        per_signer = seen.setdefault(rec.signer, {})
        if rec.plan_hash in per_signer:
            prior = per_signer[rec.plan_hash]
            if prior.recipient_set != rec.recipient_set:
                raise EquivocationDetected(
                    f"signer {rec.signer} equivocated in round {round_no}: "
                    f"plan {rec.plan_hash} sent to {prior.recipient_set} "
                    f"and {rec.recipient_set}"
                )
        else:
            per_signer[rec.plan_hash] = rec

    for signer, plans in seen.items():
        if len(plans) > 1:
            hashes = sorted(plans.keys())
            raise EquivocationDetected(
                f"signer {signer} voted for multiple plan hashes in round {round_no}: {hashes}"
            )

    consistent = [r for r in records if r.plan_hash == claimed_plan_hash]
    if len(consistent) < quorum:
        raise IncompleteCertificate(
            f"round {round_no}: only {len(consistent)} consistent votes for "
            f"{claimed_plan_hash}, need {quorum}"
        )

    return claimed_plan_hash
