# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-equivocation-detection-as-unsound-when-the-shared-task-graph-is-partially-replicated-and-quorum-certificates.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-equivocation-detection-as-unsound-when-the-shared-task-graph-is-partially-replicated-and-quorum-certificates.warrant.json
# Markdown SHA-256:   91259f2665623fc1d1e0483f3f80314c30902a3d7a78f7843b568f8ffe96746f
# Code AST SHA-256:   80c6db350c4453285ed4094bc42621555a995946e5cbaaf0c7af63946f517908
# Verified Classes:   UnanchoredEquivocationProof, DifferentParentQC, MultiWriterSlotCollision, Mutation, QuorumCertificate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnanchoredEquivocationProof(RuntimeError):
    """Raised when an equivocation proof's slot cannot be reconstructed from its cited QC chain."""


class DifferentParentQC(RuntimeError):
    """Raised when two mutations cite different parent QCs; slots are incomparable."""


class MultiWriterSlotCollision(RuntimeError):
    """Raised when the QC ordering certificate admits both deltas at the slot (concurrency, not equivocation)."""


@dataclass(frozen=True)
class Mutation:
    agent_id: str
    slot: int
    parent_qc_hash: str
    delta_hash: str
    signature: bytes


@dataclass(frozen=True)
class QuorumCertificate:
    qc_hash: str
    # ordering_cert[slot] -> set of admitted delta_hashes at that slot
    ordering_cert: dict


def verify_equivocation_proof(
    m1: Mutation,
    m2: Mutation,
    parent_qc: QuorumCertificate,
    local_replica_reconstructs_slot: bool,
) -> bool:
    """
    Returns True iff the proof is a sound equivocation claim.
    Raises on conditions that make the proof inadmissible (must not be co-signed).
    """
    if m1.agent_id != m2.agent_id:
        raise UnanchoredEquivocationProof("proof spans different agents; not equivocation")

    if m1.parent_qc_hash != m2.parent_qc_hash:
        raise DifferentParentQC(
            f"parents differ: {m1.parent_qc_hash} vs {m2.parent_qc_hash}; slots incomparable"
        )

    if m1.slot != m2.slot:
        # Different slots under same parent: legitimate concurrent edits, not equivocation.
        return False

    if not local_replica_reconstructs_slot:
        raise UnanchoredEquivocationProof(
            f"slot {m1.slot} not reconstructable from QC {parent_qc.qc_hash}; "
            "proof referent is local, not global"
        )

    admitted = parent_qc.ordering_cert.get(m1.slot, set())
    if m1.delta_hash in admitted and m2.delta_hash in admitted:
        raise MultiWriterSlotCollision(
            f"both deltas admitted at slot {m1.slot} by QC {parent_qc.qc_hash}; "
            "this is concurrency, not equivocation"
        )

    # Exactly one admitted delta, and the other mutation contradicts it.
    if len(admitted) == 1:
        admitted_delta = next(iter(admitted))
        return (m1.delta_hash == admitted_delta) != (m2.delta_hash == admitted_delta)

    # Neither delta is admitted: QC ordering cert is incomplete; refuse to adjudicate.
    raise UnanchoredEquivocationProof(
        f"QC {parent_qc.qc_hash} admits neither delta at slot {m1.slot}; "
        "ordering certificate incomplete, proof unadjudicable"
    )


def co_sign_slashing_proposal(
    m1: Mutation,
    m2: Mutation,
    parent_qc: QuorumCertificate,
    local_replica_reconstructs_slot: bool,
) -> bool:
    try:
        is_equivocation = verify_equivocation_proof(
            m1, m2, parent_qc, local_replica_reconstructs_slot
        )
    except (UnanchoredEquivocationProof, DifferentParentQC, MultiWriterSlotCollision):
        # Refuse to co-sign: the proof is inadmissible under the referent-anchoring invariant.
        return False
    return is_equivocation
