# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-equivocation-tolerant-quorums-from-collapsing-under-reputation-weighted-voting.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-equivocation-tolerant-quorums-from-collapsing-under-reputation-weighted-voting.warrant.json
# Markdown SHA-256:   e13decd346cdffa303a3d001cb38b59f2d612b814e330464fd0d47a3b62bc075
# Code AST SHA-256:   14d458305ebf420dc76454a02e9b83286b340806e133b005ca1feb9f1a71c3a4
# Verified Classes:   QuorumSnapshotError, EquivocationLivenessError, Ledger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class QuorumSnapshotError(RuntimeError):
    """Raised when numerator and denominator are drawn from different ledger epochs."""
    pass


class EquivocationLivenessError(RuntimeError):
    """Raised when an equivocation report cannot reach a confirming quorum
    because the accused's weight dominates the report-quorum."""
    pass


@dataclass
class Ledger:
    epoch: int = 0
    weights: Dict[str, float] = field(default_factory=dict)
    confirmed_equivocators: Set[str] = field(default_factory=set)

    def snapshot(self) -> "Ledger":
        return Ledger(
            epoch=self.epoch,
            weights=dict(self.weights),
            confirmed_equivocators=set(self.confirmed_equivocators),
        )


def tally_quorum(
    snapshot_open: Ledger,
    snapshot_tally: Ledger,
    yes_voters: Set[str],
    q: float = 0.67,
) -> bool:
    # Invariant: denominator and numerator must share the same epoch.
    if snapshot_open.epoch != snapshot_tally.epoch:
        raise QuorumSnapshotError(
            f"denominator epoch {snapshot_open.epoch} != numerator epoch "
            f"{snapshot_tally.epoch}; quorum is unsound"
        )

    # Frozen denominator: union of all eligible at proposal-open, minus only
    # equivocators confirmed BEFORE open. Detection during the window must not
    # shrink the denominator.
    eligible = {
        agent
        for agent in snapshot_open.weights
        if agent not in snapshot_open.confirmed_equivocators
    }
    eligible_weight = sum(snapshot_open.weights[a] for a in eligible)
    threshold = q * eligible_weight

    # Numerator: YES voters who are eligible and not confirmed equivocators
    # as of the tally snapshot. Penalty only ever removes weight here.
    yes_weight = sum(
        snapshot_tally.weights[a]
        for a in yes_voters
        if a in eligible and a not in snapshot_tally.confirmed_equivocators
    )
    return yes_weight >= threshold


def confirm_equivocation(
    ledger: Ledger,
    accused: str,
    reporter: str,
    report_quorum: float = 0.5,
) -> Ledger:
    # Report-quorum must not be weightable by the accused.
    voters = {a: w for a, w in ledger.weights.items() if a != accused}
    total = sum(voters.values())
    reporter_weight = voters.get(reporter, 0.0)
    if total == 0 or reporter_weight / total < report_quorum:
        raise EquivocationLivenessError(
            f"reporter {reporter} weight {reporter_weight:.2f} cannot reach "
            f"report-quorum {report_quorum:.2f} against accused {accused}; "
            f"penalty is deadlocked"
        )
    ledger.confirmed_equivocators.add(accused)
    ledger.epoch += 1
    return ledger
