# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-sign-a-commit-certificate-when-the-quorum-intersection-proof-is-only-probabilistic.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-sign-a-commit-certificate-when-the-quorum-intersection-proof-is-only-probabilistic.warrant.json
# Markdown SHA-256:   79dc6cbe6ede291d918a4e6d411f9f6f3fb0c25ff407b90b137ae5b30f8000e7
# Code AST SHA-256:   4d7b7d9e748543ed9c985e0f55bfd300c7ab60c58f5c3c0632b61a5939212623
# Verified Classes:   EquivocationDetected, Vote, VoteSigner
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class EquivocationDetected(RuntimeError):
    """Raised when a replica attempts to sign two values for one (height, view),
    or when a certificate contains a repeated signer identity."""
    pass


@dataclass(frozen=True)
class Vote:
    height: int
    view: int
    value_hash: str
    signer: str


class VoteSigner:
    """Enforces sign-once-per-view via durable compare-and-set on (height, view)."""

    def __init__(self, identity: str, durable_store: dict):
        self.identity = identity
        self.store = durable_store  # key: (height, view) -> value_hash

    def sign(self, height: int, view: int, value_hash: str) -> Vote:
        key = (height, view)
        prior = self.store.get(key)
        if prior is not None and prior != value_hash:
            # Retry sampled a different value: refuse, do not re-sign.
            raise EquivocationDetected(
                f"replica {self.identity} already signed {prior!r} at "
                f"(h={height}, v={view}); refusing to sign {value_hash!r}"
            )
        self.store[key] = value_hash  # CAS-equivalent for this store
        return Vote(height, view, value_hash, self.identity)


def verify_certificate(votes: list[Vote], height: int, view: int, f: int) -> str:
    """Aggregator-side guard. Counts DISTINCT signers, rejects duplicates."""
    signers = [v.signer for v in votes]
    if len(signers) != len(set(signers)):
        dupes = {s for s in signers if signers.count(s) > 1}
        raise EquivocationDetected(
            f"certificate at (h={height}, v={view}) contains repeated "
            f"signers {sorted(dupes)}; treat as Byzantine evidence, reject cert"
        )
    for v in votes:
        if (v.height, v.view) != (height, view):
            raise EquivocationDetected(
                f"vote for (h={v.height}, v={v.view}) submitted to cert at "
                f"(h={height}, v={view})"
            )
    if len(set(signers)) < 2 * f + 1:
        raise EquivocationDetected(
            f"certificate at (h={height}, v={view}) has only "
            f"{len(set(signers))} distinct signers; need {2 * f + 1}"
        )
    hashes = {v.value_hash for v in votes}
    if len(hashes) != 1:
        raise EquivocationDetected(
            f"certificate at (h={height}, v={view}) spans multiple values "
            f"{sorted(hashes)}"
        )
    return hashes.pop()


def detect_conflicting_certs(certs: dict, height: int, view: int) -> Optional[str]:
    """Two valid certs for one (height, view) means >= f+1 equivocators. Halt."""
    key = (height, view)
    if key in certs:
        raise EquivocationDetected(
            f"conflicting commit certificates at (h={height}, v={view}): "
            f"value {certs[key]!r} vs incoming; halt commitment, do not "
            f"resolve by latest-wins"
        )
    return None
