# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-reputation-slashing-quorum-is-being-gamed-by-a-byzantine-minority-before-the-slash-executes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-reputation-slashing-quorum-is-being-gamed-by-a-byzantine-minority-before-the-slash-executes.warrant.json
# Markdown SHA-256:   058a2bddd177e00f66fa7564dfc8ee9e79efd14df5991819a4043b6a36718398
# Code AST SHA-256:   501948b53f34a0dc02288d673c95bb611fb843068ca9a1b27bed22d78176d2df
# Verified Classes:   SlashingQuorumCompromised, Attestation, SlashVerdict
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class SlashingQuorumCompromised(RuntimeError):
    """Raised when a slash verdict is structurally unsound despite nominal quorum."""

    pass


@dataclass(frozen=True)
class Attestation:
    validator_id: str
    divergence_hash: str
    evidence_source_id: str  # upstream fetch provenance, NOT validator identity
    fetched_at: float


@dataclass
class SlashVerdict:
    accused_id: str
    modal_cluster: list[Attestation] = field(default_factory=list)
    lineage_count: int = 0
    quorum_reached: bool = False
    defense_window_seconds: float = 90.0
    rebuttal_cost_seconds: float = 0.0


def audit_pre_slash(
    attestations: Sequence[Attestation],
    n_validators: int,
    defense_window_seconds: float,
    rebuttal_cost_seconds: float,
    min_lineage_diversity: float = 0.66,
) -> SlashVerdict:
    f = n_validators // 3
    required = 2 * f + 1

    # 1. Cluster by divergence hash; find modal cluster.
    clusters: dict[str, list[Attestation]] = {}
    for a in attestations:
        clusters.setdefault(a.divergence_hash, []).append(a)
    modal_hash, modal = max(clusters.items(), key=lambda kv: len(kv[1]))

    # 2. Collapse fan-in: count independent evidence lineages, not identities.
    lineages = {a.evidence_source_id for a in modal}
    lineage_count = len(lineages)
    diversity = lineage_count / max(len(modal), 1)

    # 3. Rebuttal feasibility: defense window must exceed worst-case rebuttal cost.
    defense_feasible = rebuttal_cost_seconds <= defense_window_seconds

    verdict = SlashVerdict(
        accused_id="<accused>",
        modal_cluster=modal,
        lineage_count=lineage_count,
        defense_window_seconds=defense_window_seconds,
        rebuttal_cost_seconds=rebuttal_cost_seconds,
    )

    # Reject clusters that reach identity-quorum but not lineage-quorum.
    if len(modal) >= required and diversity < min_lineage_diversity:
        raise SlashingQuorumCompromised(
            f"modal cluster has {len(modal)} attestations (>= {required}) "
            f"but only {lineage_count} independent evidence lineages "
            f"(diversity={diversity:.2f} < {min_lineage_diversity}); "
            f"fan-in indicates coordinated forgery, not independent replay."
        )

    # Reject timeout-slash: absence of supermajority must NOT convert to a slash.
    if len(modal) < required:
        raise SlashingQuorumCompromised(
            f"no divergence cluster reached supermajority "
            f"({len(modal)} < {required}); timeout fallback must abstain, "
            f"not slash. Escalate to auditor quorum."
        )

    # Reject slashes where the accused cannot physically rebut within the window.
    if not defense_feasible:
        raise SlashingQuorumCompromised(
            f"rebuttal cost {rebuttal_cost_seconds:.1f}s exceeds defense window "
            f"{defense_window_seconds:.1f}s; verdict is unenforceable and must "
            f"be suspended pending window re-provisioning."
        )

    verdict.quorum_reached = True
    return verdict
