# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-during-byzantine-fault-tolerant-task-commitment-consensus-when-the-same-agent-signs-divergent-commitment-reco.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-during-byzantine-fault-tolerant-task-commitment-consensus-when-the-same-agent-signs-divergent-commitment-reco.warrant.json
# Markdown SHA-256:   870e233ac979dcc481b39e892172249a3ee2cc82dc38d54c01ccc0ee3323eba7
# Code AST SHA-256:   b9a734399f3705062acea0c697da6b88a11a2bf7a5724a20058ac6e4cf95142e
# Verified Classes:   EquivocationFault, CommitmentCertificate, EquivocationDetector
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EquivocationFault(RuntimeError):
    """Raised when a proposer has signed conflicting commitment certificates
    for the same (task_id, epoch). This is a Byzantine-proposer fault and must
    halt reconciliation; it must NOT be resolved by signature-count tiebreak."""
    pass


@dataclass(frozen=True)
class CommitmentCertificate:
    task_id: str
    epoch: int
    assignee: str
    nonce: str
    shard_id: str
    proposer_sig: str  # signature over canonical tuple; verified upstream

    def canonical_tuple(self) -> Tuple[str, int, str, str]:
        return (self.task_id, self.epoch, self.assignee, self.nonce)

    def digest(self) -> str:
        return hashlib.sha256(
            f"{self.task_id}|{self.epoch}|{self.assignee}|{self.nonce}".encode()
        ).hexdigest()


class EquivocationDetector:
    """Retains all observed certificates for the reconciliation window and
    detects same-(task_id, epoch) conflicts signed by the same proposer."""

    def __init__(self, retention_epochs: int = 2):
        self._retained: Dict[Tuple[str, int], List[CommitmentCertificate]] = {}
        self._retention_epochs = retention_epochs

    def observe(self, cert: CommitmentCertificate) -> None:
        key = (cert.task_id, cert.epoch)
        self._retained.setdefault(key, []).append(cert)

    def reconcile(self, task_id: str, epoch: int) -> CommitmentCertificate:
        key = (task_id, epoch)
        certs = self._retained.get(key, [])
        if not certs:
            raise EquivocationFault(f"no certificates retained for {key}")

        # Deduplicate identical canonical tuples (duplicate ratification).
        distinct = {c.canonical_tuple(): c for c in certs}
        if len(distinct) > 1:
            # Two or more DISTINCT commitment tuples at the same epoch.
            # Signature count is irrelevant. Halt.
            raise EquivocationFault(
                f"equivocation on {key}: proposer signed {len(distinct)} "
                f"distinct tuples: {[c.digest() for c in distinct.values()]}"
            )
        return next(iter(distinct.values()))

    def prune(self, current_epoch: int) -> None:
        cutoff = current_epoch - self._retention_epochs
        for key in [k for k in self._retained if k[1] < cutoff]:
            del self._retained[key]
