# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-peer-s-equivocation-as-a-commitment-validity-fault-rather-than-a-reconciliation-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-peer-s-equivocation-as-a-commitment-validity-fault-rather-than-a-reconciliation-retry.warrant.json
# Markdown SHA-256:   52d61388fe026936804670f495c9a58cd11449ca7b352ce9e78441f78e1c9742
# Code AST SHA-256:   e702c601ec45822b097603449904c9f1dd937b6e93bc1c0886b13a61905cfa80
# Verified Classes:   EquivocationCertificateError, Attestation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EquivocationCertificateError(RuntimeError):
    """Raised when a slot must halt due to proven signer equivocation."""


@dataclass(frozen=True)
class Attestation:
    signer_id: str
    slot: int
    nonce: int
    task_id: str
    state: str          # "ACK" | "NACK"
    signature: bytes    # verified against signer's registered key
    channel: str        # attributable fetch channel


def _content_hash(a: Attestation) -> str:
    return hashlib.sha256(f"{a.task_id}|{a.state}|{a.nonce}".encode()).hexdigest()


def classify_mismatch(
    local: Attestation,
    fetched: Attestation,
    verified_keys: Dict[str, bytes],
) -> str:
    """
    Returns one of: "DIVERGENCE", "EQUIVOCATION", "ATTRIBUTION_FAILURE".
    Never signs, never advances cursor. Pure classification.
    """
    if local.slot != fetched.slot:
        return "ATTRIBUTION_FAILURE"

    # Signature verification is a precondition for any classification.
    for a in (local, fetched):
        if a.signer_id not in verified_keys:
            return "ATTRIBUTION_FAILURE"

    # Same signer, same slot+nonce, divergent content => equivocation.
    if (
        local.signer_id == fetched.signer_id
        and local.nonce == fetched.nonce
        and _content_hash(local) != _content_hash(fetched)
    ):
        return "EQUIVOCATION"

    # Disjoint signers, same slot => recoverable divergence.
    if local.signer_id != fetched.signer_id and local.slot == fetched.slot:
        return "DIVERGENCE"

    return "ATTRIBUTION_FAILURE"


def reconcile_slot(
    local: Attestation,
    fetched_batches: List[Attestation],
    verified_keys: Dict[str, bytes],
    max_retries: int = 8,
) -> Tuple[str, Optional[Tuple[Attestation, Attestation]]]:
    """
    Reconciles a slot. On equivocation, raises with a certificate.
    On divergence, retries within bound. Never signs before classification.
    """
    certificate: Optional[Tuple[Attestation, Attestation]] = None

    for attempt in range(max_retries):
        for fetched in fetched_batches:
            verdict = classify_mismatch(local, fetched, verified_keys)

            if verdict == "EQUIVOCATION":
                certificate = (local, fetched)
                # Halt: do NOT sign, do NOT advance cursor.
                raise EquivocationCertificateError(
                    f"slot={local.slot} signer={local.signer_id} "
                    f"nonce={local.nonce} divergent states "
                    f"({local.state} vs {fetched.state}); "
                    f"certificate constructed; slot halted"
                )

            if verdict == "DIVERGENCE":
                # Safe to re-fetch; do not adopt, do not sign.
                continue

        # No equivocation found this pass; re-fetch next attempt.
        fetched_batches = _refetch(local.slot)

    # Exhausted retries without certificate and without convergence.
    raise EquivocationCertificateError(
        f"slot={local.slot} could not reconcile after {max_retries} "
        f"attempts and no equivocation certificate could be constructed; "
        f"instance must quarantine signing and request full state transfer"
    )


def _refetch(slot: int) -> List[Attestation]:
    # Placeholder: fetch attestations for slot from randomized peer subset.
    return []
