# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-equivocation-detection-horizon-when-heterogeneous-llm-agents-vote-under-bft-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-equivocation-detection-horizon-when-heterogeneous-llm-agents-vote-under-bft-consensus.warrant.json
# Markdown SHA-256:   25167571f07c3f44b5c6a578a24b0ababa5a58e6cb919442ddb6f54a50832c14
# Code AST SHA-256:   e0c711cb0418b38f8b8e4a4c205ea9fba6329f4cc787884d9df7c2aba38a90ba
# Verified Classes:   EquivocationFault, RestartStateError, SignedLog, Instance
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class EquivocationFault(RuntimeError):
    """Raised when an agent signs two distinct commitments at one (agent_id, height)."""


class RestartStateError(RuntimeError):
    """Raised when an instance attempts to sign without re-attesting current view."""


# Fields that are load-bearing for the state machine. Rationale, confidence,
# and sampling metadata are deliberately excluded: they are flavor, not commitment.
COMMITMENT_FIELDS = ("proposal_hash", "height", "view", "round", "parent_hash", "tool_effects")


def canonical_commitment(payload: dict[str, Any]) -> bytes:
    subset = {k: payload[k] for k in COMMITMENT_FIELDS if k in payload}
    return json.dumps(subset, sort_keys=True, separators=(",", ":")).encode("utf-8")


def commitment_hash(payload: dict[str, Any]) -> str:
    return hashlib.sha256(canonical_commitment(payload)).hexdigest()


@dataclass
class SignedLog:
    # key: (agent_id, height) -> set of distinct commitment hashes ever signed
    by_agent_height: dict[tuple[str, int], set[str]] = field(default_factory=dict)

    def record(self, agent_id: str, height: int, payload: dict[str, Any]) -> str:
        h = commitment_hash(payload)
        key = (agent_id, height)
        seen = self.by_agent_height.setdefault(key, set())
        if seen and h not in seen:
            raise EquivocationFault(
                f"agent {agent_id} signed distinct commitments at height {height}: "
                f"{sorted(seen)} vs {h}"
            )
        if h in seen:
            # Identical re-sign is not harmless: it fingerprints a restarted or
            # replayed instance that has lost track of its own commitments.
            raise EquivocationFault(
                f"agent {agent_id} re-signed identical commitment at height {height}: {h}"
            )
        seen.add(h)
        return h


@dataclass
class Instance:
    agent_id: str
    declared_view: int | None = None  # None == cold start, must re-attest
    log: SignedLog = field(default_factory=SignedLog)

    def reattest(self, current_view: int) -> None:
        self.declared_view = current_view

    def sign(self, payload: dict[str, Any]) -> str:
        if self.declared_view is None:
            raise RestartStateError(
                f"agent {self.agent_id} attempted to sign before view re-attestation"
            )
        if payload.get("view") != self.declared_view:
            raise RestartStateError(
                f"agent {self.agent_id} signing stale view {payload.get('view')} "
                f"!= attested {self.declared_view}"
            )
        return self.log.record(self.agent_id, int(payload["height"]), payload)


def run_round(agent: Instance, payload: dict[str, Any]) -> str:
    try:
        return agent.sign(payload)
    except (EquivocationFault, RestartStateError):
        raise
    except Exception as exc:  # noqa: BLE001 - normalize unexpected signer faults
        raise EquivocationFault(
            f"unclassified signer fault for {agent.agent_id}: {exc!r}"
        ) from exc
