# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-byzantine-quorum-capture-during-adversarial-collusion-detection-the-drift-cohort-blind-spot-in-reputation-weighted-qu.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-byzantine-quorum-capture-during-adversarial-collusion-detection-the-drift-cohort-blind-spot-in-reputation-weighted-qu.warrant.json
# Markdown SHA-256:   8f20442a63bf96f54c9dfd26344d48cad9c71176d75fd73cd0d18b573afa3497
# Code AST SHA-256:   04c748a5aeec1080c79dcc4d273943296dd5cfe4588b2f7ec0a4b7ea93edf088
# Verified Classes:   QuorumCaptureError, InsufficientContestedSample
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import math
from collections import defaultdict
from itertools import combinations

class QuorumCaptureError(RuntimeError):
    """Raised when a colluding cohort is detected via contested-stratum co-divergence."""
    pass

class InsufficientContestedSample(RuntimeError):
    """Raised when too few contested items exist to trust a co-divergence estimate."""
    pass

def contested_stratum(items, honest_ids, entropy_threshold=0.15):
    """Return items where honest agents disagree (high inter-honest entropy)."""
    contested = []
    for item in items:
        votes = [item["votes"][h] for h in honest_ids if h in item["votes"]]
        if len(set(votes)) > 1:
            # crude entropy proxy: fraction of non-modal votes
            modal = max(set(votes), key=votes.count)
            entropy = 1.0 - votes.count(modal) / len(votes)
            if entropy >= entropy_threshold:
                contested.append(item)
    return contested

def pairwise_co_divergence(contested, median_fn):
    """P(both i and j disagree with honest median | contested item)."""
    pair_disagree = defaultdict(int)
    pair_total = defaultdict(int)
    for item in contested:
        med = median_fn(item)
        agents = list(item["votes"].keys())
        for i, j in combinations(agents, 2):
            pair_total[(i, j)] += 1
            if item["votes"][i] != med and item["votes"][j] != med:
                pair_disagree[(i, j)] += 1
    return {
        pair: pair_disagree[pair] / pair_total[pair]
        for pair in pair_total
        if pair_total[pair] > 0
    }

def detect_collusion_cohort(contested, median_fn, marginal_disagree, kappa=3.0,
                            min_sample=40):
    if len(contested) < min_sample:
        raise InsufficientContestedSample(
            f"only {len(contested)} contested items; need >= {min_sample}"
        )
    co = pairwise_co_divergence(contested, median_fn)
    flagged = []
    for (i, j), observed in co.items():
        pi = marginal_disagree.get(i, 0.0)
        pj = marginal_disagree.get(j, 0.0)
        expected = pi * pj
        if expected > 0 and observed > expected * kappa:
            flagged.append((i, j, observed, expected))
    if flagged:
        cohort = {a for pair in flagged for a in pair[:2]}
        raise QuorumCaptureError(
            f"Byzantine cohort suspected: {sorted(cohort)}; "
            f"worst pair {max(flagged, key=lambda x: x[2])}"
        )
    return []
