# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-equivocation-in-byzantine-plan-commitment-consensus-when-a-proposer-signs-divergent-plan-digests-to-disjoint-quorums.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-equivocation-in-byzantine-plan-commitment-consensus-when-a-proposer-signs-divergent-plan-digests-to-disjoint-quorums.warrant.json
# Markdown SHA-256:   5bfae45eff3d002db96900352df524816ce3c61799777c845f9284ca6a1795bb
# Code AST SHA-256:   1dad2a499bac2d73eed79d9a7015dc58715bbb9cc615b2b7e05009d7c6f11a1c
# Verified Classes:   EquivocationDetected, Prepare, PlanCommitmentPeer
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Set, Tuple


class EquivocationDetected(RuntimeError):
    """Raised when a peer observes two signed plan digests for the same plan slot."""
    pass


@dataclass(frozen=True)
class Prepare:
    view: int
    plan_slot: str          # MUST be derived from committed state, not proposer seq
    digest: str
    signer: str
    signature: str


class PlanCommitmentPeer:
    def __init__(self, peer_id: str, quorum: int):
        self.peer_id = peer_id
        self.quorum = quorum
        # (view, plan_slot) -> digest this peer has signed
        self._signed: Dict[Tuple[int, str], str] = {}
        # gossip buffer of PREPAREs seen from any peer
        self._seen: Dict[Tuple[int, str], Set[Tuple[str, str]]] = {}

    def _record_and_check(self, p: Prepare) -> None:
        key = (p.view, p.plan_slot)
        self._seen.setdefault(key, set()).add((p.digest, p.signer))
        digests = {d for (d, _) in self._seen[key]}
        if len(digests) > 1:
            # Equivocation: two distinct digests for one slot.
            raise EquivocationDetected(
                f"peer {self.peer_id} observed conflicting digests {digests} "
                f"for plan slot {p.plan_slot} in view {p.view}; "
                f"aborting round and forcing view-change"
            )
        prev = self._signed.get(key)
        if prev is not None and prev != p.digest:
            raise EquivocationDetected(
                f"peer {self.peer_id} already signed {prev} for slot "
                f"{p.plan_slot}; refusing conflicting {p.digest}"
            )

    def on_prepare(self, p: Prepare) -> str:
        # Validate plan-slot derivation before anything else.
        if not self._slot_is_state_derived(p.plan_slot):
            raise EquivocationDetected(
                f"plan slot {p.plan_slot} is proposer-assigned; "
                f"cannot bound equivocation"
            )
        self._record_and_check(p)
        self._signed[(p.view, p.plan_slot)] = p.digest
        return self._sign_prepare(p)

    def _slot_is_state_derived(self, slot: str) -> bool:
        # In production: check slot == H(last_committed_digest) or agreed counter.
        return slot.startswith("slot:") and slot.count(":") >= 2

    def _sign_prepare(self, p: Prepare) -> str:
        return f"sig({self.peer_id},{p.view},{p.plan_slot},{p.digest})"

    def validate_commit_certificate(self, cert_digest: str, cert_sigs: Set[str],
                                    view: int, plan_slot: str) -> None:
        if len(cert_sigs) < self.quorum:
            raise EquivocationDetected(
                f"commit certificate has {len(cert_sigs)} sigs, quorum is {self.quorum}"
            )
        my_digest = self._signed.get((view, plan_slot))
        if my_digest is not None and my_digest != cert_digest:
            raise EquivocationDetected(
                f"commit certificate digest {cert_digest} conflicts with "
                f"locally signed digest {my_digest} for slot {plan_slot}"
            )
