# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-equivocation-collapse-in-byzantine-agent-quorums-under-partial-synchrony-with-slashing-and-reputation-decay.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-equivocation-collapse-in-byzantine-agent-quorums-under-partial-synchrony-with-slashing-and-reputation-decay.warrant.json
# Markdown SHA-256:   88556f878608db49e31a3fbd67a721afa4b0529227eca8f661937309b7542403
# Code AST SHA-256:   5aeeb31a31b350e6a611025d041c5f10fed9bb61fd1f2a4801c4d3a429847656
# Verified Classes:   EquivocationCollapseError, ProofState, Agent, EquivocationProof, Certificate, ReputationLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, Optional
from enum import Enum


class EquivocationCollapseError(RuntimeError):
    """Raised when a quorum certificate is finalized while an equivocation proof
    against one of its signers is pending attribution. This is the safety failure
    the provisional-zero invariant is designed to prevent."""
    pass


class ProofState(Enum):
    NONE = "none"
    PROVISIONAL = "provisional"   # locally detected, not yet slashed
    SLASHED = "slashed"            # slashing tx committed
    TIMED_OUT = "timed_out"        # 2Δ elapsed without slashing quorum


@dataclass
class Agent:
    agent_id: str
    base_weight: float = 1.0


@dataclass
class EquivocationProof:
    accused_id: str
    proof_hash: str
    state: ProofState = ProofState.NONE
    detected_at_ms: float = 0.0
    slashed_at_ms: Optional[float] = None


@dataclass
class Certificate:
    task_id: str
    signer_ids: Set[str]
    payload_hash: str


@dataclass
class ReputationLedger:
    agents: Dict[str, Agent] = field(default_factory=dict)
    proofs: Dict[str, EquivocationProof] = field(default_factory=dict)  # accused_id -> proof
    delta_ms: float = 500.0

    def effective_weight(self, agent_id: str, now_ms: float) -> float:
        agent = self.agents.get(agent_id)
        if agent is None:
            return 0.0
        proof = self.proofs.get(agent_id)
        if proof is None or proof.state == ProofState.NONE:
            return agent.base_weight
        if proof.state == ProofState.SLASHED:
            return 0.0
        if proof.state == ProofState.PROVISIONAL:
            # provisional-zero: equivocator contributes nothing to threshold
            return 0.0
        if proof.state == ProofState.TIMED_OUT:
            # proof failed to reach slashing quorum; slow decay applies
            return agent.base_weight * 0.5
        return agent.base_weight

    def quorum_threshold(self, n: int) -> int:
        return (2 * n) // 3 + 1

    def evaluate_certificate(self, cert: Certificate, n: int, now_ms: float) -> str:
        """Returns 'final', 'deferred', or raises EquivocationCollapseError."""
        threshold = self.quorum_threshold(n)
        weight_sum = 0.0
        pending_deferral = False
        for signer in cert.signer_ids:
            proof = self.proofs.get(signer)
            if proof is not None and proof.state == ProofState.PROVISIONAL:
                # signer is under provisional penalty; certificate cannot finalize
                pending_deferral = True
            weight_sum += self.effective_weight(signer, now_ms)

        if pending_deferral:
            # defer until slashing commits or 2Δ elapses
            return "deferred"

        if weight_sum < threshold:
            # under provisional-zero this means a signer was provisionally zeroed
            # and the remaining weight is insufficient. If any signer is SLASHED
            # but the certificate was already accepted elsewhere, that is collapse.
            slashed_signers = [
                s for s in cert.signer_ids
                if self.proofs.get(s) and self.proofs[s].state == ProofState.SLASHED
            ]
            if slashed_signers:
                raise EquivocationCollapseError(
                    f"Certificate {cert.task_id} signs with slashed agent(s) "
                    f"{slashed_signers}; finality divergence across honest nodes"
                )
            return "rejected"

        return "final"


def finalize_certificate(
    ledger: ReputationLedger,
    cert: Certificate,
    n: int,
    now_ms: float,
    already_accepted_elsewhere: bool,
) -> str:
    verdict = ledger.evaluate_certificate(cert, n, now_ms)
    if verdict == "deferred":
        # schedule re-evaluation at now_ms + 2*delta
        return "deferred"
    if verdict == "final":
        # invariant: if any signer is slashed, this must never be 'final'
        for signer in cert.signer_ids:
            proof = ledger.proofs.get(signer)
            if proof is not None and proof.state == ProofState.SLASHED:
                raise EquivocationCollapseError(
                    f"Invariant violation: certificate {cert.task_id} finalized "
                    f"with slashed signer {signer} at t={now_ms}ms"
                )
        return "final"
    if already_accepted_elsewhere:
        raise EquivocationCollapseError(
            f"Certificate {cert.task_id} rejected locally but accepted by peer; "
            f"reputation view divergence detected"
        )
    return "rejected"
