# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-fold-a-reputation-weighted-quorum-it-can-still-numerically-satisfy.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-fold-a-reputation-weighted-quorum-it-can-still-numerically-satisfy.warrant.json
# Markdown SHA-256:   bb24d73b31fe384caabcf7f59b1ed0ac169ba945d34480bb2f8ec28f57e632a7
# Code AST SHA-256:   9a5ef8c9893838efa04efdf690601e42f841cae7258deea7358e102a62c58abb
# Verified Classes:   QuorumFoldRefused, PeerWeight, FoldContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class QuorumFoldRefused(RuntimeError):
    """Raised when a reputation-weighted quorum clears threshold but is not validly composed."""


@dataclass
class PeerWeight:
    peer_id: str
    weight: float
    last_delta_seq: int          # causal sequence of the reputation delta that set this weight
    last_observed_verdict_seq: int  # most recent verdict signed by this peer that we've seen
    is_default: bool = False
    delegate_of: str | None = None


@dataclass
class FoldContext:
    q: float
    total_weight: float
    verdicts: list[PeerWeight] = field(default_factory=list)


def fold_quorum(ctx: FoldContext) -> str:
    # Collapse delegates into their countersigner's slot; delegates are not independently weight-bearing.
    folded: dict[str, float] = {}
    for v in ctx.verdicts:
        key = v.delegate_of or v.peer_id
        folded[key] = folded.get(key, 0.0) + v.weight

    weighted_sum = sum(folded.values())
    threshold = ctx.q * ctx.total_weight
    slack = weighted_sum - threshold

    if weighted_sum < threshold:
        return "NO_QUORUM"  # ordinary quorum loss; not this failure mode

    # Invariant 1: no positive default weights may participate in crossing threshold.
    default_contribution = sum(v.weight for v in ctx.verdicts if v.is_default)
    if default_contribution > 0.0:
        raise QuorumFoldRefused(
            f"default-weight peers contributed {default_contribution:.3f} to a fold with slack {slack:.3f}; "
            f"defaults are a mint, not evidence"
        )

    # Invariant 2: stale weights (delta older than peer's last observed verdict) must not exceed slack.
    stale = sum(
        v.weight for v in ctx.verdicts
        if v.last_delta_seq < v.last_observed_verdict_seq
    )
    if stale > slack:
        raise QuorumFoldRefused(
            f"stale-weight contribution {stale:.3f} exceeds slack {slack:.3f}; "
            f"quorum satisfied only by pre-behavior reputation"
        )

    # Invariant 3: single-peer concentration must not exceed half the threshold.
    if folded and max(folded.values()) > threshold / 2.0:
        top_peer = max(folded, key=folded.get)
        raise QuorumFoldRefused(
            f"peer {top_peer} contributes {folded[top_peer]:.3f} > half-threshold {threshold/2:.3f}; "
            f"this is a single-peer quorum, not a federation quorum"
        )

    return "COMMIT"
