# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-peer-agent-that-signs-two-conflicting-attestations-for-the-same-task-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-peer-agent-that-signs-two-conflicting-attestations-for-the-same-task-commitment.warrant.json
# Markdown SHA-256:   67ad43ac262fc13e13acf378eb7696d5c4acbb6cf99f651597b8d1c7af455827
# Code AST SHA-256:   f3211373a9029a6e831cd73750ce977b415aad0e351f489c43f2dde177e2b699
# Verified Classes:   EquivocationDetected, CommitmentNotPinned, Attestation, CommitmentIndex
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class EquivocationDetected(RuntimeError):
    """Raised when two conflicting attestations bind the same commitment to different results."""
    pass


class CommitmentNotPinned(RuntimeError):
    """Raised when a commitment ID is not deterministically derived and cannot be deduplicated."""
    pass


@dataclass(frozen=True)
class Attestation:
    commitment_id: str
    result_hash: str
    signer: str
    epoch: int
    attempt: int = 0
    supersedes: Optional[str] = None  # result_hash of the attestation this replaces


@dataclass
class CommitmentIndex:
    # commitment_id -> canonical Attestation once committed
    committed: dict = field(default_factory=dict)
    # commitment_id -> list of pending Attestations awaiting quorum resolution
    pending: dict = field(default_factory=dict)

    def _derive_commitment_id(self, task_spec: str) -> str:
        # Commitment IDs MUST be derived from the task spec, never coordinator-minted.
        if not task_spec or len(task_spec) < 8:
            raise CommitmentNotPinned(
                f"task_spec too short to derive a stable commitment id: {task_spec!r}"
            )
        return hashlib.sha256(task_spec.encode()).hexdigest()[:16]

    def observe(self, att: Attestation) -> str:
        cid = att.commitment_id
        if cid in self.committed:
            canonical = self.committed[cid]
            if canonical.result_hash != att.result_hash:
                # Conflicting attestation against an already-committed value.
                raise EquivocationDetected(
                    f"signer={att.signer} attested {att.result_hash} for committed "
                    f"commitment {cid} whose canonical result is {canonical.result_hash}"
                )
            return "accepted_duplicate"

        prior = self.pending.get(cid, [])
        for p in prior:
            if p.result_hash == att.result_hash:
                return "accepted_duplicate_pending"
            # Honest re-execution must carry an explicit supersedes pointer.
            if att.supersedes == p.result_hash and att.attempt > p.attempt:
                self.pending[cid] = [att]
                return "accepted_superseding"
            if p.supersedes == att.result_hash and p.attempt > att.attempt:
                return "rejected_stale"

        if prior and not any(
            a.supersedes or b.supersedes for a in prior for b in [att]
        ):
            # Two unlinked attestations for the same commitment: equivocation suspected.
            self.pending[cid] = prior + [att]
            raise EquivocationDetected(
                f"unlinked conflicting attestations for commitment {cid}: "
                f"{[a.result_hash for a in prior + [att]]} from signers "
                f"{[a.signer for a in prior + [att]]}"
            )

        self.pending.setdefault(cid, []).append(att)
        return "accepted_pending"

    def commit(self, cid: str, quorum_hashes: list[str]) -> Attestation:
        if len(set(quorum_hashes)) != 1:
            raise EquivocationDetected(
                f"quorum for {cid} disagrees: {quorum_hashes}"
            )
        candidates = [a for a in self.pending.get(cid, []) if a.result_hash == quorum_hashes[0]]
        if not candidates:
            raise EquivocationDetected(
                f"quorum hash {quorum_hashes[0]} has no matching pending attestation for {cid}"
            )
        chosen = candidates[0]
        self.committed[cid] = chosen
        self.pending.pop(cid, None)
        return chosen
