# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-equivocates-during-bft-consensus-the-split-view-quorum-trap-in-llm-agent-committees.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-equivocates-during-bft-consensus-the-split-view-quorum-trap-in-llm-agent-committees.warrant.json
# Markdown SHA-256:   0c99b3135f452622777a9f763ab6b79676db01dab76e787607d29a21eb1a138e
# Code AST SHA-256:   402caaec2b88ded58cbcf010c9d0bf24909574ceabd62efcc3c1953d7733e53b
# Verified Classes:   SplitViewQuorumError, Vote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from hashlib import sha256
from typing import Iterable


class SplitViewQuorumError(RuntimeError):
    """Raised when a quorum certificate would aggregate votes across
    differing context bundles or view epochs (unsafe merge)."""


@dataclass(frozen=True)
class Vote:
    agent_id: str
    proposal_hash: str
    context_bundle_hash: str
    view_epoch: int
    decision: str  # "APPROVE" | "REJECT"
    signature: str

    def content_key(self) -> tuple[str, str, int]:
        return (self.proposal_hash, self.context_bundle_hash, self.view_epoch)


def certify_quorum(
    votes: Iterable[Vote],
    proposal_hash: str,
    quorum_size: int,
) -> dict:
    """Build a quorum certificate only from votes that share a single
    (proposal_hash, context_bundle_hash, view_epoch) tuple.

    Refuses to merge across views or context bundles even when distinct
    identities would sum to quorum_size.
    """
    relevant = [v for v in votes if v.proposal_hash == proposal_hash]
    if not relevant:
        raise SplitViewQuorumError(
            f"no votes for proposal {proposal_hash[:12]}"
        )

    # Group by full content key, not by proposal hash alone.
    groups: dict[tuple[str, str, int], dict[str, Vote]] = {}
    for v in relevant:
        key = v.content_key()
        groups.setdefault(key, {})
        # Identity collision within a single key = true equivocation.
        if v.agent_id in groups[key] and groups[key][v.agent_id].decision != v.decision:
            raise SplitViewQuorumError(
                f"agent {v.agent_id} equivocated within view {v.view_epoch} "
                f"on identical context {v.context_bundle_hash[:12]}"
            )
        groups[key][v.agent_id] = v

    # A valid certificate must live entirely inside ONE group.
    for key, members in groups.items():
        approvals = {a for a, v in members.items() if v.decision == "APPROVE"}
        if len(approvals) >= quorum_size:
            return {
                "proposal_hash": proposal_hash,
                "context_bundle_hash": key[1],
                "view_epoch": key[2],
                "approvers": sorted(approvals),
            }

    # No single view/context reached quorum. Detect the unsafe-merge temptation.
    distinct_approvers = {
        v.agent_id for v in relevant if v.decision == "APPROVE"
    }
    if len(distinct_approvers) >= quorum_size:
        best = max(len({a for a, v in m.items() if v.decision == "APPROVE"})
                   for m in groups.values())
        raise SplitViewQuorumError(
            f"split-view quorum trap: {len(distinct_approvers)} distinct approvers "
            f"across views but max in-view approvals = {best} < {quorum_size}; "
            f"refusing cross-view merge for proposal {proposal_hash[:12]}"
        )

    raise SplitViewQuorumError(
        f"insufficient quorum for proposal {proposal_hash[:12]}: "
        f"best single-view approval count below {quorum_size}"
    )
