# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-peer-s-signed-commitment-as-revoked-the-equivocation-window-invariant-in-bft-agent-ledgers.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-peer-s-signed-commitment-as-revoked-the-equivocation-window-invariant-in-bft-agent-ledgers.warrant.json
# Markdown SHA-256:   b9fadeb4060804dfcc24c2f4c255154ee2d862bd658f3f63e7ef48b0d61359e4
# Code AST SHA-256:   d3252a563b28a2df2a797daba02470c2d4e1ad0936447499e5e2ee92faa75275
# Verified Classes:   ForkEquivocationError, Commitment, LedgerView
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ForkEquivocationError(RuntimeError):
    """Raised when two valid signatures under one key cannot be causally ordered."""


@dataclass
class Commitment:
    key_id: str
    slot: str
    digest: str
    counter: int
    prev_hash: str          # hash-chain link to signer's prior commitment
    signature: bytes = b""


@dataclass
class LedgerView:
    # key_id -> last accepted commitment (the head of that key's chain)
    heads: dict = field(default_factory=dict)
    # (key_id, slot) -> commitment currently prepared/committed
    slots: dict = field(default_factory=dict)


def _verify(commitment: Commitment, pubkey: bytes) -> bool:
    # Placeholder for real Ed25519 verification; must cover all signed fields.
    payload = f"{commitment.key_id}|{commitment.slot}|{commitment.digest}|" \
              f"{commitment.counter}|{commitment.prev_hash}".encode()
    return hmac.compare_digest(
        hmac.new(pubkey, payload, hashlib.sha256).digest(), commitment.signature
    )


def _chain_links(earlier: Commitment, later: Commitment) -> bool:
    """True iff `later` provably descends from `earlier` in the signer's chain."""
    return (
        later.counter == earlier.counter + 1
        and later.prev_hash == hashlib.sha256(
            f"{earlier.key_id}|{earlier.slot}|{earlier.digest}|{earlier.counter}".encode()
        ).hexdigest()
    )


def ingest_commitment(
    view: LedgerView,
    incoming: Commitment,
    pubkey: bytes,
) -> str:
    """
    Returns one of: 'accepted', 'superseded', 'frozen'.
    Raises ForkEquivocationError when the incoming message collides with an
    existing commitment for the same (key, slot) and cannot be causally ordered.
    """
    if not _verify(incoming, pubkey):
        raise ForkEquivocationError(
            f"signature invalid for key={incoming.key_id} slot={incoming.slot}"
        )

    slot_key = (incoming.key_id, incoming.slot)
    existing: Optional[Commitment] = view.slots.get(slot_key)

    if existing is None:
        view.slots[slot_key] = incoming
        view.heads[incoming.key_id] = incoming
        return "accepted"

    if existing.digest == incoming.digest and existing.counter == incoming.counter:
        return "accepted"  # idempotent replay

    # Same signer, same slot, divergent content: can we order them?
    if _chain_links(existing, incoming):
        view.slots[slot_key] = incoming
        view.heads[incoming.key_id] = incoming
        return "superseded"

    if _chain_links(incoming, existing):
        return "superseded"  # we already hold the later one

    # Equal counter, no chain link, divergent digest => equivocation window.
    # Local tiebreak is forbidden; freeze and escalate to quorum.
    raise ForkEquivocationError(
        "equivocation window: key={k} slot={s} has two valid commitments "
        "(counter={c1} digest={d1}) vs (counter={c2} digest={d2}); "
        "no causal order provable — freeze slot and broadcast evidence pair".format(
            k=incoming.key_id, s=incoming.slot,
            c1=existing.counter, d1=existing.digest[:12],
            c2=incoming.counter, d2=incoming.digest[:12],
        )
    )
