# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-heterogeneous-model-quorum-drift-as-a-byzantine-equivocation-before-committing-a-shared-plan.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-heterogeneous-model-quorum-drift-as-a-byzantine-equivocation-before-committing-a-shared-plan.warrant.json
# Markdown SHA-256:   c4124bffae052cda8ed63e1720be8c91fd9ae699dc345197b4b448d4db908843
# Code AST SHA-256:   02f708438b688682a9c421bf950a0cd279a00e6e3393563da6940a5e97fb9837
# Verified Classes:   QuorumContaminationError, Ballot
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from collections import defaultdict
from dataclasses import dataclass, field


class QuorumContaminationError(RuntimeError):
    """Raised when equivocating voters could have inflated an apparent quorum."""
    pass


@dataclass
class Ballot:
    voter_id: str
    audit_id: str
    plan_hash: str
    signature_ok: bool


def canonical_hash(steps: list[str]) -> str:
    # sorted keys + normalized whitespace; near-identical plans must not diverge on formatting
    canon = "\n".join(sorted(s.strip().lower() for s in steps))
    return hashlib.sha256(canon.encode()).hexdigest()


def reconcile_and_commit(
    ballots: list[Ballot],
    n_voters: int,
    f: int,
) -> str:
    # Step 1: drop invalid signatures before anything else
    valid = [b for b in ballots if b.signature_ok]

    # Step 2: per-voter ledger of distinct hashes signed across auditors
    ledger: dict[str, set[str]] = defaultdict(set)
    for b in valid:
        ledger[b.voter_id].add(b.plan_hash)

    equivocators = {v for v, hashes in ledger.items() if len(hashes) >= 2}

    # Step 3: equivocation accounting BEFORE tally (the invariant)
    if len(equivocators) > f:
        raise QuorumContaminationError(
            f"{len(equivocators)} equivocating voters exceeds fault budget f={f}; "
            f"quorum arithmetic is unreliable"
        )

    # Step 4: tally only non-equivocating voters, per hash
    endorsers: dict[str, set[str]] = defaultdict(set)
    for b in valid:
        if b.voter_id in equivocators:
            continue
        endorsers[b.plan_hash].add(b.voter_id)

    required = 2 * f + 1
    winners = [h for h, vs in endorsers.items() if len(vs) >= required]

    if len(winners) > 1:
        raise QuorumContaminationError(
            f"multiple hashes reached {required} distinct non-equivocating endorsers: {winners}"
        )
    if not winners:
        raise QuorumContaminationError(
            f"no hash reached {required} distinct non-equivocating endorsers; "
            f"re-vote with hardened auditor context required"
        )
    return winners[0]
