# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-counts-a-colluding-quorum-as-honest-equivocation-weighted-bft-quorums-in-multi-agent-decision-rounds.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-counts-a-colluding-quorum-as-honest-equivocation-weighted-bft-quorums-in-multi-agent-decision-rounds.warrant.json
# Markdown SHA-256:   2dd99d7832168d248d7aae5b88f9550f2a446de0c59531b0031631209bddc8ac
# Code AST SHA-256:   32315a52e8c10587b5a3a644ed99952e09fb907c26ca7b4d0ffef8d59489dfc1
# Verified Classes:   EquivocationDetected, QuorumNotCertifiable, Attestation, EquivocationGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, Tuple


class EquivocationDetected(RuntimeError):
    """Raised when an agent signs two conflicting attestations at the same sequence."""


class QuorumNotCertifiable(RuntimeError):
    """Raised when a local count cannot be promoted to a committed decision."""


@dataclass(frozen=True)
class Attestation:
    agent_id: str
    seq: int
    payload_hash: str
    prev_hash: str

    def digest(self) -> str:
        raw = f"{self.agent_id}:{self.seq}:{self.payload_hash}:{self.prev_hash}"
        return hashlib.sha256(raw.encode()).hexdigest()


@dataclass
class EquivocationGuard:
    # (agent_id, seq) -> digest of the single attestation we have accepted
    seen: Dict[Tuple[str, int], str] = field(default_factory=dict)
    evicted: set = field(default_factory=set)

    def observe(self, att: Attestation) -> None:
        key = (att.agent_id, att.seq)
        d = att.digest()
        prior = self.seen.get(key)
        if prior is not None and prior != d:
            # Two distinct attestations at the same sequence: provable fault.
            self.evicted.add(att.agent_id)
            raise EquivocationDetected(
                f"agent {att.agent_id} equivocated at seq {att.seq}: "
                f"{prior[:12]}.. != {d[:12]}.."
            )
        self.seen[key] = d


def certify_quorum(
    guard: EquivocationGuard,
    attestations: list,
    n: int,
    f: int,
    payload_hash: str,
) -> set:
    """Certify a 2f+1 quorum over a single view, refusing evicted agents."""
    threshold = 2 * f + 1
    voters = set()
    for att in attestations:
        guard.observe(att)  # may raise EquivocationDetected
        if att.agent_id in guard.evicted:
            continue
        if att.payload_hash != payload_hash:
            continue
        voters.add(att.agent_id)

    if len(voters) < threshold:
        raise QuorumNotCertifiable(
            f"only {len(voters)}/{n} honest-matching votes for {payload_hash[:12]}..; "
            f"need {threshold}; evicted={sorted(guard.evicted)}"
        )

    # Safety check: the quorum must contain more than f non-evicted agents,
    # guaranteeing at least one honest agent in any intersecting quorum.
    if len(voters) - len(guard.evicted & voters) <= f:
        raise QuorumNotCertifiable(
            "quorum margin exhausted by evicted agents; view not certifiable"
        )
    return voters


# --- demonstration of the bifurcation boundary ---
guard = EquivocationGuard()
h_s_prime = hashlib.sha256(b"S->S'").hexdigest()
h_rollback = hashlib.sha256(b"S->S").hexdigest()

# Colluder C sends commit(S') to A,B and rollback to D,E at the same seq.
c_to_ab = Attestation("C", 7, h_s_prime, prev_hash="0" * 64)
c_to_de = Attestation("C", 7, h_rollback, prev_hash="0" * 64)

guard.observe(c_to_ab)
try:
    guard.observe(c_to_de)
except EquivocationDetected as e:
    print(f"[bounded] {e} -> C evicted, single view enforced")
