# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-when-an-agent-s-signed-task-result-differs-across-quorum-replicas-but-each-replica-s-merkle-proof-verifies-lo.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-when-an-agent-s-signed-task-result-differs-across-quorum-replicas-but-each-replica-s-merkle-proof-verifies-lo.warrant.json
# Markdown SHA-256:   311ce4ec63e28e91be8845b01fc80f82b48139f27a54b4d034ac4f33b44b6926
# Code AST SHA-256:   6506b5110edb5296a5891d95d1b0d5c42a94774e3d0898ccbc553c8cf576504c
# Verified Classes:   EquivocationDetected, Signature
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Dict, List, Tuple


class EquivocationDetected(RuntimeError):
    """Raised when a single replica signed two digests for one (task, parent, view)."""


@dataclass(frozen=True)
class Signature:
    replica_id: str
    task_id: str
    parent_digest: str
    view: int
    result_digest: str
    sig: bytes  # opaque; verified by verify_sig() below


def verify_sig(s: Signature, replica_pubkey: Dict[str, bytes]) -> bool:
    # Placeholder for real Ed25519 verification; must bind all fields.
    expected = hashlib.sha256(
        f"{s.task_id}|{s.parent_digest}|{s.view}|{s.result_digest}".encode()
    ).digest()
    return replica_pubkey.get(s.replica_id) == expected[:32]


def detect_equivocation(
    sigs: List[Signature], replica_pubkey: Dict[str, bytes]
) -> Tuple[str, str, str, int]:
    """Return (replica_id, task, parent, view) proving equivocation, or raise if none.

    A conflict witness exists iff some replica emitted >=2 valid signatures over
    DIFFERENT result_digest values for the SAME (task_id, parent_digest, view).
    """
    seen: Dict[Tuple[str, str, str, int], Dict[str, bytes]] = {}
    for s in sigs:
        if not verify_sig(s, replica_pubkey):
            continue  # invalid sigs are not witnesses
        key = (s.replica_id, s.task_id, s.parent_digest, s.view)
        bucket = seen.setdefault(key, {})
        bucket[s.result_digest] = s.sig
        if len(bucket) >= 2:
            return (s.replica_id, s.task_id, s.parent_digest, s.view)
    raise EquivocationDetected("no witness found in supplied signature set")


def accept_result(
    sigs: List[Signature],
    replica_pubkey: Dict[str, bytes],
    f: int,
) -> str:
    """Accept a result only under the non-equivocation predicate.

    Raises EquivocationDetected if a witness exists; raises ValueError if the
    quorum or uniqueness condition fails.
    """
    try:
        witness = detect_equivocation(sigs, replica_pubkey)
    except EquivocationDetected:
        witness = None

    if witness is not None:
        rid, task, parent, view = witness
        raise EquivocationDetected(
            f"replica {rid} signed conflicting digests for "
            f"task={task} parent={parent} view={view}"
        )

    # No witness: require f+1 valid signatures over a SINGLE digest.
    valid = [s for s in sigs if verify_sig(s, replica_pubkey)]
    if not valid:
        raise ValueError("no valid signatures")
    digests = {s.result_digest for s in valid}
    if len(digests) != 1:
        # Disagreement without a per-replica witness: indeterminate, must halt.
        raise EquivocationDetected(
            f"indeterminate: multiple digests {digests} with no single-replica witness"
        )
    digest = digests.pop()
    signers = {s.replica_id for s in valid if s.result_digest == digest}
    if len(signers) < f + 1:
        raise ValueError(f"quorum not met: {len(signers)} < {f + 1}")
    return digest
