# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-sign-a-second-commitment-after-observing-equivocation-in-a-leaderless-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-sign-a-second-commitment-after-observing-equivocation-in-a-leaderless-quorum.warrant.json
# Markdown SHA-256:   6445777c61dd88761e4f659245451405f01f7f899fb823f6ffcadb7989fc0bb1
# Code AST SHA-256:   b37f043fcbc8090a69a9784d35806d05591ca78bf453a3a5630f2a9551d93084
# Verified Classes:   EquivocationDetected, Vote, AgentState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class EquivocationDetected(RuntimeError):
    """Raised when a peer has signed two distinct values for one (epoch, round)."""
    pass


@dataclass(frozen=True)
class Vote:
    agent: str
    epoch: str
    round: int
    value: str
    signature: bytes  # opaque; assumed non-repudiable


@dataclass
class AgentState:
    agent_id: str
    observed: Dict[Tuple[str, str, int], List[Vote]] = field(default_factory=dict)
    poisoned_epochs: set = field(default_factory=set)

    def record(self, vote: Vote) -> None:
        key = (vote.agent, vote.epoch, vote.round)
        self.observed.setdefault(key, []).append(vote)


def sign_vote(state: AgentState, epoch: str, round: int, value: str) -> Vote:
    """Pre-signature gate: refuse to sign a poisoned epoch, and refuse to sign
    if any peer has equivocated in this epoch (even in an earlier round)."""
    if epoch in state.poisoned_epochs:
        raise EquivocationDetected(
            f"agent {state.agent_id} refuses to sign epoch {epoch}: epoch poisoned"
        )

    for (peer, ep, rnd), votes in state.observed.items():
        if ep != epoch:
            continue
        values = {v.value for v in votes}
        if len(values) > 1:
            state.poisoned_epochs.add(epoch)
            # evidence broadcast is the caller's responsibility; we halt locally.
            raise EquivocationDetected(
                f"agent {state.agent_id} observed peer {peer} signing "
                f"{sorted(values)} in epoch {epoch} round {rnd}; "
                f"refusing to add signature to poisoned epoch"
            )

    vote = Vote(state.agent_id, epoch, round, value, signature=b"\x00")
    state.record(vote)
    return vote


def tally_quorum(state: AgentState, epoch: str, round: int, q: int) -> str:
    """Tally only counts votes from non-equivocating peers in a non-poisoned epoch."""
    if epoch in state.poisoned_epochs:
        raise EquivocationDetected(
            f"refusing to tally poisoned epoch {epoch}"
        )
    counts: Dict[str, int] = {}
    for (peer, ep, rnd), votes in state.observed.items():
        if ep != epoch or rnd != round:
            continue
        if len({v.value for v in votes}) > 1:
            state.poisoned_epochs.add(epoch)
            raise EquivocationDetected(
                f"equivocator {peer} present in quorum set for {epoch}/{round}"
            )
        counts[votes[-1].value] = counts.get(votes[-1].value, 0) + 1
    for value, n in counts.items():
        if n >= q:
            return value
    raise EquivocationDetected(
        f"no quorum for epoch {epoch} round {round}; possible stall, not a commit"
    )
