# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-byzantine-equivocation-in-heterogeneous-llm-agent-consensus-before-quorum-collapse.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-byzantine-equivocation-in-heterogeneous-llm-agent-consensus-before-quorum-collapse.warrant.json
# Markdown SHA-256:   f8c41ff81414a6e6fd581b14a0c4e336185c5c0506a61714bd9e5001fd595b28
# Code AST SHA-256:   335933c115bfb83672e283d578aa60e5dd03fa3f5b7c0d9965d75a64ef72863b
# Verified Classes:   EquivocationClassificationError, Ballot
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Literal


class EquivocationClassificationError(RuntimeError):
    """Raised when a ballot pair cannot be classified under the tuple rule."""


@dataclass(frozen=True)
class Ballot:
    round: int
    agent_id: str
    prompt_digest: str
    sampling_seed: int
    transition: Literal["ACCEPT", "REJECT"]
    evidence_pointers: tuple[str, ...]
    signature: bytes


def classify_ballot_pair(a: Ballot, b: Ballot) -> str:
    if a.agent_id != b.agent_id or a.round != b.round:
        raise EquivocationClassificationError(
            f"ballots not from same agent/round: {a.agent_id}@{a.round} vs {b.agent_id}@{b.round}"
        )
    same_digest = a.prompt_digest == b.prompt_digest
    same_seed = a.sampling_seed == b.sampling_seed
    agree = a.transition == b.transition

    if same_digest and same_seed and not agree:
        return "HARD_FAULT"
    if same_digest and same_seed and agree:
        return "DUPLICATE_IDENTICAL"
    if not same_digest and not agree:
        return "CONTESTED_REVOTE"
    if not same_digest and agree:
        return "LEGITIMATE_REVOTE_AGREE"
    if same_digest and not same_seed and not agree:
        return "STOCHASTIC_DIVERGENCE"
    raise EquivocationClassificationError(
        f"unreachable tuple combination for {a.agent_id}@{a.round}"
    )


def resolve_round(ballots: list[Ballot], quorum: int) -> str:
    by_agent: dict[str, list[Ballot]] = {}
    for b in ballots:
        by_agent.setdefault(b.agent_id, []).append(b)

    contested_agents: list[str] = []
    effective: dict[str, str] = {}
    for agent, group in by_agent.items():
        if len(group) == 1:
            effective[agent] = group[0].transition
            continue
        if len(group) > 2:
            raise EquivocationClassificationError(
                f"agent {agent} emitted {len(group)} ballots in one round; tuple rule undefined"
            )
        verdict = classify_ballot_pair(group[0], group[1])
        if verdict == "HARD_FAULT":
            raise EquivocationClassificationError(
                f"quarantine {agent}: identical (digest, seed) with divergent transitions"
            )
        if verdict == "CONTESTED_REVOTE":
            contested_agents.append(agent)
            continue
        effective[agent] = group[0].transition if verdict != "STOCHASTIC_DIVERGENCE" else "PENDING"

    if contested_agents:
        return f"ROUND_HELD: contested={contested_agents}; request digest-pinned revote"

    accept = sum(1 for t in effective.values() if t == "ACCEPT")
    reject = sum(1 for t in effective.values() if t == "REJECT")
    if accept >= quorum:
        return "COMMIT_ACCEPT"
    if reject >= quorum:
        return "COMMIT_REJECT"
    return "NO_QUORUM"
