# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-collusive-reputation-inflation-when-sybil-identities-reuse-a-shared-provenance-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-collusive-reputation-inflation-when-sybil-identities-reuse-a-shared-provenance-chain.warrant.json
# Markdown SHA-256:   7281754710ef2a6a7cc632df810506c81ff731bf58db2b025c0246f5981c0ea5
# Code AST SHA-256:   e6d24ad2963afe5aecd0cc880f54634396263e7369d1b31c2ea53f4cdb4d61a4
# Verified Classes:   ProvenanceCollapseError, Attestation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceCollapseError(RuntimeError):
    """Raised when a reputation aggregate is structurally Sybil-vulnerable
    because its attesters reduce to too few independent provenance roots."""
    pass


@dataclass
class Attestation:
    key_id: str
    root_id: str          # terminal signing event / sandbox epoch
    nonce_lineage: str    # underlying work event hash
    outcome: float        # 0..1
    weight: float


def aggregate_reputation(target: str, atts: list[Attestation],
                         k_min_roots: int = 5,
                         max_root_collapse: float = 3.0) -> float:
    # 1. Deduplicate to provenance roots BEFORE weighting.
    seen_lineages: set[str] = set()
    root_weight: dict[str, float] = {}
    root_outcomes: dict[str, list[float]] = {}

    for a in atts:
        if a.nonce_lineage in seen_lineages:
            continue  # re-attestation of same work: not a new observation
        seen_lineages.add(a.nonce_lineage)
        root_weight[a.root_id] = root_weight.get(a.root_id, 0.0) + a.weight
        root_outcomes.setdefault(a.root_id, []).append(a.outcome)

    n_keys = len({a.key_id for a in atts})
    n_roots = len(root_weight)

    if n_roots < k_min_roots:
        raise ProvenanceCollapseError(
            f"target={target} has {n_keys} keys but only {n_roots} provenance "
            f"roots (< k_min_roots={k_min_roots}); structurally Sybil-vulnerable"
        )

    collapse = n_keys / max(n_roots, 1)
    if collapse > max_root_collapse:
        # Only reject if convergence is ALSO outcome-uniform (collusive signature).
        entropies = []
        for outs in root_outcomes.values():
            p = sum(outs) / len(outs)
            entropies.append(0.0 if p in (0.0, 1.0)
                             else -(p * __import__("math").log(p) +
                                    (1 - p) * __import__("math").log(1 - p)))
        mean_entropy = sum(entropies) / len(entropies)
        if mean_entropy < 0.1:  # uniform-positive convergence
            raise ProvenanceCollapseError(
                f"target={target} root-collapse={collapse:.2f} with "
                f"outcome entropy {mean_entropy:.3f}; collusive inflation suspected"
            )

    total = sum(root_weight.values())
    return sum(root_weight[r] * (sum(root_outcomes[r]) / len(root_outcomes[r]))
               for r in root_weight) / total if total else 0.0
