# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-quorum-capture-by-a-colluding-heterogeneous-coalition-before-committing-a-validated-result.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-quorum-capture-by-a-colluding-heterogeneous-coalition-before-committing-a-validated-result.warrant.json
# Markdown SHA-256:   2531baef7a2c3a837775ccae7758c2cbaa3a623f353ea77169018d39e5f45cea
# Code AST SHA-256:   429dea4ba7bf321573ae08948e37dc92db9714829bad9cc264d6b54af359af24
# Verified Classes:   QuorumCaptureError, Attestation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from collections import defaultdict
from dataclasses import dataclass


class QuorumCaptureError(RuntimeError):
    """Raised when raw quorum is met but cluster-weighted quorum is not."""
    pass


@dataclass
class Attestation:
    validator_id: str
    cluster_id: str          # family / toolchain / shared-corpus identifier
    value_hash: str


def cluster_weighted_quorum(
    attestations: list[Attestation],
    n_validators: int,
    f: int,
    correlation_threshold: float = 0.85,
) -> str:
    """
    Collapse correlated clusters to single logical votes before counting.
    A cluster votes for the value its members most agree on, weighted by
    its internal agreement rate; clusters below threshold count normally.
    """
    if n_validators < 3 * f + 1:
        raise QuorumCaptureError(
            f"swarm size {n_validators} cannot tolerate f={f} "
            f"(need >= {3 * f + 1})"
        )

    by_value = defaultdict(list)
    for a in attestations:
        by_value[a.value_hash].append(a)

    # Build cluster -> dominant value and internal agreement rate
    cluster_votes: dict[str, tuple[str, float, int]] = {}
    cluster_members = defaultdict(list)
    for a in attestations:
        cluster_members[a.cluster_id].append(a)

    for cid, members in cluster_members.items():
        counts = defaultdict(int)
        for m in members:
            counts[m.value_hash] += 1
        dominant, dom_count = max(counts.items(), key=lambda kv: kv[1])
        agreement = dom_count / len(members)
        cluster_votes[cid] = (dominant, agreement, len(members))

    # Weighted tally: correlated clusters count as ONE vote; independent
    # clusters count by size.
    weighted = defaultdict(float)
    for cid, (dom, agreement, size) in cluster_votes.items():
        if agreement >= correlation_threshold and size > 1:
            weighted[dom] += 1.0          # collapse to single logical voter
        else:
            weighted[dom] += float(size)

    winner, win_weight = max(weighted.items(), key=lambda kv: kv[1])
    raw_count = sum(1 for a in attestations if a.value_hash == winner)

    # Raw quorum met but cluster-weighted quorum not -> capture
    if raw_count >= 2 * f + 1 and win_weight < (2 * f + 1):
        raise QuorumCaptureError(
            f"raw quorum {raw_count} met for {winner[:8]} but "
            f"cluster-weighted weight {win_weight:.1f} < {2 * f + 1}; "
            f"suspected quorum capture by correlated coalition"
        )

    # Largest single cluster exceeding f on winning side is always suspect
    largest_win_cluster = max(
        (size for cid, (dom, _, size) in cluster_votes.items() if dom == winner),
        default=0,
    )
    if largest_win_cluster > f:
        raise QuorumCaptureError(
            f"winning side depends on a single cluster of size "
            f"{largest_win_cluster} > f={f}; partition independence violated"
        )

    return winner
