# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-casts-a-quorum-vote-before-its-tool-call-ledger-is-sealed-byzantine-equivocation-through-heterogeneous-verifier-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-casts-a-quorum-vote-before-its-tool-call-ledger-is-sealed-byzantine-equivocation-through-heterogeneous-verifier-disagree.warrant.json
# Markdown SHA-256:   b2029df17b49d58b56720cce7affab25dd3e708df1bf3ee2349674901093d088
# Code AST SHA-256:   b4dc50418a29933a15a4548d3de661c741320b41495f7d716efeca115a8e7d85
# Verified Classes:   EquivocationSuspect, VoteEnvelope, RoundState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EquivocationSuspect(RuntimeError):
    """Raised when a quorum is reached without causal closure of the vote set,
    or when two envelopes from the same sender in the same round disagree."""
    pass


@dataclass(frozen=True)
class VoteEnvelope:
    sender_id: str
    recipient_id: str
    round_id: str
    nonce: str
    claim: str
    vote: str                 # "ACCEPT" | "REJECT"
    evidence_digest: str      # MUST cover tool OUTPUTS, not just inputs
    signature: str            # MUST cover (sender, recipient, round, nonce, claim, vote, evidence_digest)


@dataclass
class RoundState:
    f: int
    envelopes: List[VoteEnvelope] = field(default_factory=list)
    acked_digests: Dict[str, set] = field(default_factory=dict)  # sender -> set of envelope hashes acked


def _env_hash(env: VoteEnvelope) -> str:
    blob = json.dumps(env.__dict__, sort_keys=True).encode()
    return hashlib.sha256(blob).hexdigest()


def count_quorum(state: RoundState, quorum: int) -> str:
    """Return COMMIT only if quorum reached AND causal closure holds AND no equivocation."""
    # 1. Detect per-sender equivocation within the round.
    by_sender: Dict[str, List[VoteEnvelope]] = {}
    for env in state.envelopes:
        by_sender.setdefault(env.sender_id, []).append(env)
    for sender, envs in by_sender.items():
        votes = {e.vote for e in envs}
        if len(votes) > 1:
            raise EquivocationSuspect(
                f"sender {sender} emitted divergent votes {votes} in round "
                f"{envs[0].round_id}; abort and evict sender"
            )

    # 2. Count votes.
    accepts = sum(1 for e in state.envelopes if e.vote == "ACCEPT")
    if accepts < quorum:
        return "ABORT_INSUFFICIENT"

    # 3. Causal closure: every voter must have acked every other voter's envelope hash.
    voter_ids = {e.sender_id for e in state.envelopes}
    all_hashes = {_env_hash(e) for e in state.envelopes}
    for voter in voter_ids:
        acked = state.acked_digests.get(voter, set())
        if not all_hashes.issubset(acked):
            raise EquivocationSuspect(
                f"quorum {accepts}>={quorum} reached but voter {voter} has not "
                f"causally acked all envelopes; round is suspect, do not commit"
            )
    return "COMMIT"


def run_round(f: int, envelopes: List[VoteEnvelope], acks: Dict[str, set]) -> str:
    state = RoundState(f=f, envelopes=envelopes, acked_digests=acks)
    quorum = 2 * f + 1
    return count_quorum(state, quorum)
