# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quorum-signed-task-commitments-from-surviving-equivocating-verifier-agents-in-bft-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quorum-signed-task-commitments-from-surviving-equivocating-verifier-agents-in-bft-reconciliation.warrant.json
# Markdown SHA-256:   ede86ac70019f129057051d4b3ee5fd9e33a7bd5952923790c35ea3e6eca6008
# Code AST SHA-256:   cd1f313e1f6f2482fb552b5f9cbb7b6bf15ed3818f7cfbda50d607b603b099e0
# Verified Classes:   EquivocationDetected, Signature
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationDetected(RuntimeError):
    """Raised when two distinct payloads claim quorum in the same (task_id, view)."""
    pass


@dataclass(frozen=True)
class Signature:
    signer: str
    task_id: str
    view: int
    payload_hash: str
    sig: str  # opaque; verified elsewhere against (task_id, view, payload_hash)


def _preimage(task_id: str, view: int, payload_hash: str) -> str:
    return hashlib.sha256(f"{task_id}|{view}|{payload_hash}".encode()).hexdigest()


def reconcile_commitment(
    task_id: str,
    view: int,
    signatures: list[Signature],
    threshold: int,
    verify_sig,  # callable(sig, preimage) -> bool
) -> str:
    """
    Returns the single quorum-ratified payload_hash for (task_id, view).
    Raises EquivocationDetected if >1 payload_hash reaches threshold OR if any
    signer appears under two payload_hashes in the same view.
    """
    by_payload: dict[str, set[str]] = {}
    signer_to_payload: dict[str, str] = {}

    for s in signatures:
        if s.task_id != task_id or s.view != view:
            continue
        if not verify_sig(s.sig, _preimage(s.task_id, s.view, s.payload_hash)):
            # signature does not bind this payload; do not count it
            continue
        prior = signer_to_payload.get(s.signer)
        if prior is not None and prior != s.payload_hash:
            raise EquivocationDetected(
                f"signer {s.signer} signed two payloads in view {view}: "
                f"{prior} vs {s.payload_hash}"
            )
        signer_to_payload[s.signer] = s.payload_hash
        by_payload.setdefault(s.payload_hash, set()).add(s.signer)

    quorums = [ph for ph, signers in by_payload.items() if len(signers) >= threshold]
    if len(quorums) > 1:
        raise EquivocationDetected(
            f"task {task_id} view {view}: multiple payloads reached threshold: {quorums}"
        )
    if not quorums:
        raise EquivocationDetected(
            f"task {task_id} view {view}: no payload reached threshold {threshold}"
        )
    return quorums[0]
