# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-bft-agent-swarm-when-the-quorum-certificate-itself-is-the-only-witness.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-bft-agent-swarm-when-the-quorum-certificate-itself-is-the-only-witness.warrant.json
# Markdown SHA-256:   8b0f450d5cd4bda92461112e155f78563544d2b4888eeb7cf4753543234ff64d
# Code AST SHA-256:   cec0fea14920a754858e25bc116536e3358b269c5cc9d0665ccd23b599a12a43
# Verified Classes:   EquivocationDetected, MissingWitnessRecord, QuorumCertificate, PrepareRecord, CommitmentLedger
# 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 an agent holds two valid QCs for the same (task_id, height)
    with differing proposal digests, or when it discovers it double-signed."""
    pass


class MissingWitnessRecord(RuntimeError):
    """Raised when an agent cannot classify itself as witness or culprit
    because the retained prepare record was garbage-collected."""
    pass


@dataclass(frozen=True)
class QuorumCertificate:
    task_id: str
    height: int
    view: int
    proposal_digest: str
    signatures: tuple  # (replica_id, sig) pairs; assumed pre-verified


@dataclass
class PrepareRecord:
    task_id: str
    height: int
    view: int
    proposal_digest: str
    signed_at_ms: int


@dataclass
class CommitmentLedger:
    # committed[(task_id, height)] -> QC that authorized the commitment
    committed: dict = field(default_factory=dict)
    # retained_prepares[(task_id, height)] -> the single digest this agent signed
    retained_prepares: dict = field(default_factory=dict)
    # dispute window: heights below this watermark may be GC'd
    finalized_watermark: int = -1


def _semantic_digest(task_id: str, height: int, payload: bytes) -> str:
    # Digest binds task identity and height, NOT the envelope nonce/timestamp.
    h = hashlib.sha256()
    h.update(task_id.encode())
    h.update(height.to_bytes(8, "big"))
    h.update(payload)
    return h.hexdigest()


def sign_prepare(ledger: CommitmentLedger, task_id: str, height: int,
                 view: int, proposal_digest: str, now_ms: int) -> PrepareRecord:
    key = (task_id, height)
    existing = ledger.retained_prepares.get(key)
    if existing is not None and existing.proposal_digest != proposal_digest:
        # We already signed a different digest at this height. Refuse to
        # double-sign; this is the local invariant that prevents us from
        # becoming a culprit in a future equivocation proof.
        raise EquivocationDetected(
            f"refusing to double-sign {key}: already signed {existing.proposal_digest}, "
            f"asked to sign {proposal_digest}"
        )
    rec = PrepareRecord(task_id, height, view, proposal_digest, now_ms)
    ledger.retained_prepares[key] = rec
    return rec


def accept_commitment(ledger: CommitmentLedger, qc: QuorumCertificate) -> str:
    """Returns 'COMMITTED', 'DUPLICATE_BENIGN', 'HALT_EQUIVOCATION', or 'HALT_INDETERMINATE'."""
    key = (qc.task_id, qc.height)
    prior: Optional[QuorumCertificate] = ledger.committed.get(key)

    if prior is None:
        ledger.committed[key] = qc
        return "COMMITTED"

    if prior.proposal_digest == qc.proposal_digest:
        return "DUPLICATE_BENIGN"

    # Two valid QCs, same (task_id, height), different digests: equivocation.
    retained = ledger.retained_prepares.get(key)
    if retained is None:
        # Cannot classify witness vs culprit; freeze, do not auto-resolve.
        raise MissingWitnessRecord(
            f"equivocation at {key} but no retained prepare; cannot attribute fault"
        )

    if retained.proposal_digest == prior.proposal_digest:
        # We signed only the first digest -> we are a witness, not a culprit.
        raise EquivocationDetected(
            f"WITNESS at {key}: signed {retained.proposal_digest}, "
            f"observed conflicting QC {qc.proposal_digest}; emitting proof"
        )
    if retained.proposal_digest == qc.proposal_digest:
        # We signed only the second -> witness to the other branch.
        raise EquivocationDetected(
            f"WITNESS at {key}: signed {retained.proposal_digest}, "
            f"observed conflicting QC {prior.proposal_digest}; emitting proof"
        )
    # We signed both -> we are a culprit (we double-signed).
    raise EquivocationDetected(
        f"CULPRIT at {key}: self-double-signed; self-halt and escalate"
    )


def gc_prepares(ledger: CommitmentLedger, watermark: int) -> None:
    """Drop retained prepares only below the finalized dispute watermark."""
    stale = [k for k in ledger.retained_prepares if k[1] < watermark]
    for k in stale:
        del ledger.retained_prepares[k]
    ledger.finalized_watermark = watermark
