# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-org-reputation-score-laundering-from-poisoning-a2a-task-routing.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-org-reputation-score-laundering-from-poisoning-a2a-task-routing.warrant.json
# Markdown SHA-256:   da3aa9625558184b6edfdc9d873862a5b7733fa477ff474276110e7736ac4b68
# Code AST SHA-256:   d71788d82889ad635f63526cd8e652d80020ab4f454beef5d98dd79e6f1fe604
# Verified Classes:   ReputationLaunderingError, ReputationExport
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass


class ReputationLaunderingError(RuntimeError):
    """Raised when a cross-org reputation export cannot support the
    confidence required for a high-stakes A2A route."""


@dataclass(frozen=True)
class ReputationExport:
    agent_id: str
    score: float            # in [0, 1]
    sample_count: int       # nominal attestation count
    distinct_attester_keys: int  # MUST be exported; 0 means unknown


def effective_sample_size(export: ReputationExport) -> float:
    """Pessimistic n_eff under worst-case clustering.

    If all attestations share one key, n_eff collapses to 1. As the number
    of distinct keys approaches sample_count, n_eff approaches sample_count.
    """
    n = export.sample_count
    k = export.distinct_attester_keys
    if n <= 0:
        return 0.0
    if k <= 0:
        # Unknown independence: assume worst case, single key.
        return 1.0
    k = min(k, n)
    # Worst-case correlation given k distinct keys contributing n attestations.
    rho = (n - k) / (n - 1) if n > 1 else 0.0
    return n / (1.0 + (n - 1) * rho)


def route_confidence(export: ReputationExport, required_confidence: float) -> float:
    """Return the lower confidence bound the router may rely on, or raise
    if the export cannot support the required confidence."""
    n_eff = effective_sample_size(export)
    if n_eff < 2.0:
        raise ReputationLaunderingError(
            f"agent {export.agent_id}: n_eff={n_eff:.2f} from "
            f"sample_count={export.sample_count}, "
            f"distinct_keys={export.distinct_attester_keys}; "
            f"insufficient independent evidence for required "
            f"confidence {required_confidence:.3f}"
        )
    # Wilson lower bound at 95% using n_eff, not n.
    p = export.score
    z = 1.96
    denom = 1.0 + z * z / n_eff
    center = p + z * z / (2.0 * n_eff)
    margin = z * math.sqrt(p * (1.0 - p) / n_eff + z * z / (4.0 * n_eff * n_eff))
    lower = (center - margin) / denom
    if lower < required_confidence:
        raise ReputationLaunderingError(
            f"agent {export.agent_id}: lower bound {lower:.3f} < required "
            f"{required_confidence:.3f} (n_eff={n_eff:.2f}); refusing route"
        )
    return lower


def select_executor(candidates, required_confidence):
    viable = []
    for c in candidates:
        try:
            lb = route_confidence(c, required_confidence)
            viable.append((lb, c))
        except ReputationLaunderingError:
            continue
    if not viable:
        raise ReputationLaunderingError(
            "no candidate passed the independence-discounted confidence gate"
        )
    viable.sort(key=lambda t: t[0], reverse=True)
    return viable[0][1]
