# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-agent-s-equivocation-as-a-quorum-valid-vote-before-the-detection-window-closes.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-agent-s-equivocation-as-a-quorum-valid-vote-before-the-detection-window-closes.warrant.json
# Markdown SHA-256:   e00a1dd34438f3cbd7a7f9a273796e7af481969a1c4f66c650f5f75be8208746
# Code AST SHA-256:   704fc3196911eae24cbf4771b83b80c0a41e5b3e7f8f383e8c6899d8a1249bab
# Verified Classes:   EquivocationQuorumError, Vote, RoundLog
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EquivocationQuorumError(RuntimeError):
    """Raised when a round's vote set cannot be reconciled to a single
    non-equivocating quorum within the dissemination window."""
    pass


@dataclass
class Vote:
    signer: str
    result_hash: str
    round_id: int
    signature: str


@dataclass
class RoundLog:
    round_id: int
    votes_by_signer: Dict[str, List[Vote]] = field(default_factory=dict)

    def record(self, vote: Vote) -> None:
        self.votes_by_signer.setdefault(vote.signer, []).append(vote)

    def equivocators(self) -> List[str]:
        return [
            s for s, vs in self.votes_by_signer.items()
            if len({v.result_hash for v in vs}) > 1
        ]


def tally_with_global_reconciliation(
    log: RoundLog,
    honest_set: List[str],
    quorum: int,
    dissemination_complete: bool,
) -> str:
    # Guardrail 1: refuse to tally a partial view. A partial view lets a
    # Byzantine agent's two votes each reach a disjoint quorum without any
    # local detector firing. Abort instead of tallying.
    if not dissemination_complete:
        raise EquivocationQuorumError(
            f"round {log.round_id}: dissemination incomplete; "
            f"cannot distinguish equivocation from partition. Aborting."
        )

    # Guardrail 2: write-conflict resolution. Any signer with >1 result hash
    # in the round is excluded wholesale; its votes count toward nothing.
    bad = set(log.equivocators())
    if bad:
        # Log the equivocation for attribution, then exclude entirely.
        pass

    tallies: Dict[str, int] = {}
    for signer in honest_set:
        if signer in bad:
            continue
        for v in log.votes_by_signer.get(signer, []):
            tallies[v.result_hash] = tallies.get(v.result_hash, 0) + 1

    winners = [h for h, c in tallies.items() if c >= quorum]
    if len(winners) != 1:
        raise EquivocationQuorumError(
            f"round {log.round_id}: quorum not uniquely achieved after "
            f"excluding equivocators {sorted(bad)}; tallies={tallies}, "
            f"quorum={quorum}. Refusing to finalize."
        )
    return winners[0]
