# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-counts-a-hallucinating-peer-as-a-silent-abstention-the-equivocation-blind-quorum-invariant-in-byzantine-agent-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-counts-a-hallucinating-peer-as-a-silent-abstention-the-equivocation-blind-quorum-invariant-in-byzantine-agent-consensus.warrant.json
# Markdown SHA-256:   db5a6d122762a4966f3ad567add7c16820e6e73377704af8c41035378d7f0afd
# Code AST SHA-256:   f0728078e3766cf58b3652181ce49c26ce90c04864212d766544db8652c671c0
# Verified Classes:   EquivocationFault, Vote, QuorumCounter
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EquivocationFault(RuntimeError):
    """Raised when one agent signs two different sides for the same epoch."""


@dataclass
class Vote:
    agent_id: str
    epoch: int
    proposal_hash: str
    side: str          # "yes" | "no"
    signature: bytes    # sign(epoch || proposal_hash || side)


@dataclass
class QuorumCounter:
    n: int
    f: int
    threshold: int = field(init=False)
    # (agent_id, epoch) -> side, plus the conflicting signature for proof
    seen: Dict[Tuple[str, int], str] = field(default_factory=dict)
    conflicts: Dict[Tuple[str, int], Tuple[bytes, bytes]] = field(default_factory=dict)

    def __post_init__(self):
        self.threshold = 2 * self.f + 1

    def record(self, vote: Vote) -> None:
        key = (vote.agent_id, vote.epoch)
        prev = self.seen.get(key)
        if prev is None:
            self.seen[key] = vote.side
            return
        if prev != vote.side:
            # Equivocation detected: same agent, same epoch, opposite sides.
            # Both signatures are valid; this is a safety violation, not a liveness one.
            self.conflicts[key] = (self.conflicts.get(key, (b"", b""))[0], vote.signature)
            raise EquivocationFault(
                f"agent {vote.agent_id} signed both '{prev}' and '{vote.side}' "
                f"in epoch {vote.epoch} for proposal {vote.proposal_hash}"
            )

    def tally(self, epoch: int, side: str) -> int:
        if any(k[1] == epoch for k in self.conflicts):
            raise EquivocationFault(
                f"epoch {epoch} has open equivocation proofs; refusing to tally"
            )
        return sum(1 for (aid, ep), s in self.seen.items() if ep == epoch and s == side)

    def commit(self, epoch: int, side: str) -> bool:
        count = self.tally(epoch, side)
        if count >= self.threshold:
            return True
        return False


def authorize_destructive_action(counter: QuorumCounter, epoch: int, vote: Vote) -> bool:
    counter.record(vote)  # may raise EquivocationFault
    if counter.commit(epoch, "yes"):
        return True
    if counter.commit(epoch, "no"):
        return False
    raise EquivocationFault(
        f"epoch {epoch} has no quorum yet; do not execute irreversible actions"
    )
