# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-equivocation-collapse-when-byzantine-agents-vote-on-shared-state-commits-under-partial-synchrony.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-equivocation-collapse-when-byzantine-agents-vote-on-shared-state-commits-under-partial-synchrony.warrant.json
# Markdown SHA-256:   38cd325649e6de7b5367d95b66f2d65680dd4c4584da17bd89b03d3d32431363
# Code AST SHA-256:   b7d19a51edc74f33fbacb7feb19cb33a0988d0d91f3dbe56fe10cfb79344e29c
# Verified Classes:   EquivocationCollapse, SignedVote, VotingAgent
# Defensive Guards:   8 fail-closed invariants (zero external deps)

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


class EquivocationCollapse(RuntimeError):
    """Raised when an agent attempts to sign a second, different value
    for the same (index, view), or when a quorum certificate fails
    view-binding / intersection validation."""
    pass


@dataclass(frozen=True)
class SignedVote:
    agent_id: str
    index: int
    view: int
    value_hash: str
    signature: str  # opaque; in production, ed25519 over the tuple below

    def payload(self) -> bytes:
        return f"{self.index}|{self.view}|{self.value_hash}".encode()


class VotingAgent:
    def __init__(self, agent_id: str, signer):
        self.agent_id = agent_id
        self._signer = signer
        # Durable, write-ahead: (index, view) -> SignedVote
        self._frozen: Dict[Tuple[int, int], SignedVote] = {}

    def vote(self, index: int, view: int, value_hash: str, model_fn) -> SignedVote:
        key = (index, view)
        # INVARIANT 2: vote immutability per (index, view).
        # Retries MUST replay the stored signature, never re-invoke the model.
        if key in self._frozen:
            existing = self._frozen[key]
            if existing.value_hash != value_hash:
                raise EquivocationCollapse(
                    f"agent {self.agent_id} already signed {existing.value_hash} "
                    f"at (index={index}, view={view}); refusing to sign {value_hash}"
                )
            return existing  # idempotent resend of transport

        # First invocation for this (index, view): model runs exactly once.
        chosen = model_fn(index, view)  # stochastic; must not be re-run
        sv = SignedVote(
            agent_id=self.agent_id,
            index=index,
            view=view,
            value_hash=chosen,
            signature=self._signer(self.agent_id, index, view, chosen),
        )
        self._frozen[key] = sv  # persist BEFORE transmit
        return sv


def validate_certificate(cert: list[SignedVote], verify_sig) -> str:
    """INVARIANT 1: view-bound certificates. All votes must share (index, view)
    and every signature must verify over the full tuple."""
    if not cert:
        raise EquivocationCollapse("empty certificate")
    index, view = cert[0].index, cert[0].view
    seen = {}
    for sv in cert:
        if sv.index != index or sv.view != view:
            raise EquivocationCollapse(
                f"certificate mixes (index,view): saw ({sv.index},{sv.view}) "
                f"expected ({index},{view})"
            )
        if sv.agent_id in seen and seen[sv.agent_id] != sv.value_hash:
            raise EquivocationCollapse(
                f"agent {sv.agent_id} signed two values in one certificate"
            )
        seen[sv.agent_id] = sv.value_hash
        if not verify_sig(sv.agent_id, sv.index, sv.view, sv.value_hash, sv.signature):
            raise EquivocationCollapse(f"bad signature from {sv.agent_id}")
    values = set(seen.values())
    if len(values) != 1:
        raise EquivocationCollapse(f"certificate covers multiple values: {values}")
    return values.pop()


def commit_intersect(cert_a: list[SignedVote], cert_b: list[SignedVote]) -> None:
    """INVARIANT 3: any two certificates for the same index must share an
    honest signer whose two signatures are identical. Mismatch = proof."""
    map_a = {sv.agent_id: sv.value_hash for sv in cert_a}
    map_b = {sv.agent_id: sv.value_hash for sv in cert_b}
    shared = set(map_a) & set(map_b)
    if not shared:
        raise EquivocationCollapse("certificates do not intersect; quorum fault")
    for agent in shared:
        if map_a[agent] != map_b[agent]:
            raise EquivocationCollapse(
                f"equivocation proof: {agent} signed {map_a[agent]} and {map_b[agent]}"
            )
