# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-peer-agent-when-every-signed-commitment-it-receives-is-individually-valid.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-peer-agent-when-every-signed-commitment-it-receives-is-individually-valid.warrant.json
# Markdown SHA-256:   ce60b352d4829dfc24620464f77a00529c169ec33a56252222376d1970772cdb
# Code AST SHA-256:   d90b180174e9f1983858694297bf71e1ded6d477715ac7c32c0ea3069dd48a1e
# Verified Classes:   EquivocationDetected, Commitment, CommitmentLog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationDetected(RuntimeError):
    """Raised when a signer emits two distinct commitments at the same height."""


@dataclass(frozen=True)
class Commitment:
    signer: str
    height: int
    task: str
    signature: bytes

    def payload_hash(self) -> str:
        return hashlib.sha256(f"{self.height}:{self.task}".encode()).hexdigest()


class CommitmentLog:
    """Per-signer, per-height conflict store. Detection happens at ingest."""

    def __init__(self):
        self._seen: dict[tuple[str, int], Commitment] = {}
        self._proofs: list[tuple[Commitment, Commitment]] = []

    def ingest(self, c: Commitment, verify) -> None:
        if not verify(c.signature, c.task, c.signer):
            raise ValueError(f"bad signature from {c.signer}")
        key = (c.signer, c.height)
        prior = self._seen.get(key)
        if prior is None:
            self._seen[key] = c
            return
        if prior.payload_hash() == c.payload_hash():
            return  # duplicate, benign
        # Two valid signatures, same (signer, height), different payloads.
        self._proofs.append((prior, c))
        raise EquivocationDetected(
            f"signer={c.signer} height={c.height} "
            f"task_a={prior.task!r} task_b={c.task!r}"
        )


def build_quorum(log: CommitmentLog, height: int, task: str, quorum: int) -> list[Commitment]:
    members = [
        c for (s, h), c in log._seen.items()
        if h == height and c.task == task
    ]
    if len(members) < quorum:
        raise EquivocationDetected(
            f"cannot finalize height={height} task={task!r}: "
            f"only {len(members)}/{quorum} distinct signers with no conflict"
        )
    return members
