# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-commit-a-plan-under-byzantine-quorum-when-its-own-vote-is-the-deciding-ballot.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-commit-a-plan-under-byzantine-quorum-when-its-own-vote-is-the-deciding-ballot.warrant.json
# Markdown SHA-256:   d2204e6ae14c44473424f7f19120548c19f340239afcae576ea64a7532dcbd94
# Code AST SHA-256:   cfc5bd7b44b3dff45e5cd4c10b9cb21252c23c956acb592953eaef523367dd75
# Verified Classes:   DecidingBallotEquivocationError, SignedVote, VoteCollector
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class DecidingBallotEquivocationError(RuntimeError):
    """Raised when a marginal voter cannot safely cast the deciding ballot."""


@dataclass(frozen=True)
class SignedVote:
    signer: str
    plan_hash: str
    view: int
    signature: bytes


@dataclass
class VoteCollector:
    own_id: str
    current_view: int
    quorum: int
    votes: List[SignedVote] = field(default_factory=list)

    def _valid_for_counting(self, v: SignedVote) -> bool:
        # Check 1: view monotonicity. Stale-view votes are replay artifacts.
        if v.view < self.current_view:
            return False
        # Check 2: hash singularity is enforced at collection time below.
        return True

    def collect(self, incoming: SignedVote) -> Optional[str]:
        """Returns committed plan_hash if quorum reached, else None.
        Raises if this vote would be deciding but cannot be validated."""
        if not self._valid_for_counting(incoming):
            return None  # quarantine stale vote, do not count

        # Hash singularity: all counted votes must share one plan hash.
        hashes = {v.plan_hash for v in self.votes if self._valid_for_counting(v)}
        if hashes and incoming.plan_hash not in hashes:
            # Divergent hash in same view: do not count, escalate.
            raise DecidingBallotEquivocationError(
                f"hash divergence: {incoming.plan_hash} vs {hashes}"
            )

        prospective = len([v for v in self.votes if self._valid_for_counting(v)]) + 1
        is_deciding = prospective == self.quorum

        if is_deciding:
            # Check 3: self-exclusion — own signature must not already
            # appear in another quorum certificate this epoch.
            if self._own_sig_in_other_cert(incoming.plan_hash):
                raise DecidingBallotEquivocationError(
                    "own signature already committed to another plan hash"
                )
            # All three checks passed; safe to cast the deciding ballot.
            self.votes.append(incoming)
            return incoming.plan_hash

        self.votes.append(incoming)
        return None

    def _own_sig_in_other_cert(self, plan_hash: str) -> bool:
        # Placeholder: query the epoch cert log for prior own-signed certs.
        return False


def commit_plan(collector: VoteCollector, incoming: SignedVote) -> Optional[str]:
    """Commit only on a full certificate, never on a boolean quorum flag."""
    try:
        return collector.collect(incoming)
    except DecidingBallotEquivocationError:
        # Refuse to decide; escalate to view-change. Safe failure.
        raise
