# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-quorum-slice-when-reputation-weighted-voting-produces-a-supermajority-that-violates-the-local-tr.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-quorum-slice-when-reputation-weighted-voting-produces-a-supermajority-that-violates-the-local-tr.warrant.json
# Markdown SHA-256:   f70b9894f0459d871ed30488d19e1aeee5f009e934aa7fb6a38db8a55dc32934
# Code AST SHA-256:   49cfdffab33098b572e2dd6e549b4142bcfbb5adf2ca5053bbda46873a565b9c
# Verified Classes:   SliceQuorumDivergence, QuorumSlice, RoundSnapshot
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Mapping


class SliceQuorumDivergence(RuntimeError):
    """Raised when a global reputation-weighted supermajority passes the
    threshold but the instance's own quorum slice does not endorse it.

    This is a hard safety fault: committing in this state violates the FBA
    intersection property and produces non-replayable decisions.
    """


@dataclass(frozen=True)
class QuorumSlice:
    members: frozenset[str]
    threshold: float  # t_i, e.g. 0.67


@dataclass(frozen=True)
class RoundSnapshot:
    """Weights frozen at round-open. Mid-round reputation refresh is rejected."""
    weights: Mapping[str, float]
    snapshot_hash: str


def evaluate_quorum(
    instance_id: str,
    slice_: QuorumSlice,
    votes: Mapping[str, bool],
    snapshot: RoundSnapshot,
) -> bool:
    """Evaluate quorum for one instance under reputation-weighted FBA.

    Returns True only if the slice-local normalized tally meets threshold.
    Raises SliceQuorumDivergence if the global tally passes but the local
    slice-local tally does not.
    """
    # --- Global tally (necessary, NOT sufficient) ---
    total_w = sum(snapshot.weights.values())
    if total_w <= 0:
        raise SliceQuorumDivergence(
            f"{instance_id}: empty global weight pool in snapshot "
            f"{snapshot.snapshot_hash}"
        )
    global_tally = sum(
        snapshot.weights.get(a, 0.0) for a, v in votes.items() if v
    ) / total_w

    # --- Slice-local tally (the actual FBA test) ---
    slice_members = slice_.members
    missing = slice_members - snapshot.weights.keys()
    if missing:
        raise SliceQuorumDivergence(
            f"{instance_id}: slice members {sorted(missing)} absent from "
            f"weight snapshot {snapshot.snapshot_hash}; cannot normalize locally"
        )
    slice_total = sum(snapshot.weights[a] for a in slice_members)
    if slice_total <= 0:
        raise SliceQuorumDivergence(
            f"{instance_id}: zero total weight within own slice"
        )
    local_tally = sum(
        snapshot.weights[a]
        for a in slice_members
        if votes.get(a, False)
    ) / slice_total

    global_ok = global_tally >= slice_.threshold
    local_ok = local_tally >= slice_.threshold

    if global_ok and not local_ok:
        raise SliceQuorumDivergence(
            f"{instance_id}: divergent supermajority — global_tally="
            f"{global_tally:.3f} >= {slice_.threshold}, but slice-local_tally="
            f"{local_tally:.3f} < {slice_.threshold} over slice "
            f"{sorted(slice_members)}. Refusing to commit; "
            f"snapshot={snapshot.snapshot_hash}"
        )
    return local_ok


def commit_round(
    instance_id: str,
    slice_: QuorumSlice,
    votes: Mapping[str, bool],
    snapshot: RoundSnapshot,
    commit_log: list,
) -> None:
    if evaluate_quorum(instance_id, slice_, votes, snapshot):
        commit_log.append({
            "instance": instance_id,
            "snapshot_hash": snapshot.snapshot_hash,
            "slice": sorted(slice_.members),
            "committed": True,
        })
    # If evaluate_quorum raises, no commit record is written — the round
    # must be re-run with frozen weights or fall back to slice-local voting.
