# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-peer-s-slashing-warrant-replay-window-divergence-in-federated-agent-reputation-markets.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-peer-s-slashing-warrant-replay-window-divergence-in-federated-agent-reputation-markets.warrant.json
# Markdown SHA-256:   abd8b88bfe2ef787485361c570e01521cc3737024f20f14d3d9e84099f86fa3e
# Code AST SHA-256:   d4a4dcdf1437fd5dd33bad4dca10293b063a9f8cc224a3eec6536b68c72bb430
# Verified Classes:   WarrantApplicabilityError, Verdict, Warrant, LedgerView
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class WarrantApplicabilityError(RuntimeError):
    """Raised when a slashing warrant cannot be classified as apply/defer/escalate."""


class Verdict(Enum):
    APPLY = "apply"
    DEFER = "defer"
    ESCALATE = "escalate"


@dataclass(frozen=True)
class Warrant:
    issuer: str
    worker: str
    task: str
    epoch_boundary: int
    slot: str
    amount: int
    precondition_hash: str  # hash over (slot_balance, applied_set_root) at issuer's view
    signature: str


@dataclass
class LedgerView:
    head_epoch: int
    slot_balances: dict
    applied_warrants: set  # {(worker, slot, epoch_boundary)}
    applied_set_root: str

    def recompute_precondition_hash(self, slot: str, epoch: int) -> str:
        h = hashlib.sha256()
        h.update(f"{slot}:{self.slot_balances.get(slot, 0)}:{epoch}:{self.applied_set_root}".encode())
        return h.hexdigest()


def classify_warrant(w: Warrant, view: LedgerView, max_withhold_epochs: int = 3) -> Verdict:
    if not w.signature:
        raise WarrantApplicabilityError(f"warrant from {w.issuer} lacks signature")

    # Withholding bound: a warrant older than the window is void, not a peer fault.
    if view.head_epoch - w.epoch_boundary > max_withhold_epochs:
        raise WarrantApplicabilityError(
            f"warrant for {w.worker}/{w.slot}@{w.epoch_boundary} exceeded withhold window "
            f"(head={view.head_epoch})"
        )

    # Staleness: epoch boundary not yet fully replicated -> defer, never reject.
    if w.epoch_boundary > view.head_epoch:
        return Verdict.DEFER

    key = (w.worker, w.slot, w.epoch_boundary)
    if key in view.applied_warrants:
        # Idempotent replay: already applied, no-op.
        return Verdict.APPLY

    # The decisive check: does the issuer's reasoned-over state match ours at this boundary?
    if view.recompute_precondition_hash(w.slot, w.epoch_boundary) != w.precondition_hash:
        # Two honest auditors reasoned over divergent replicas of the same slot.
        # This is a double-allocation event, not evidence of issuer dishonesty.
        return Verdict.ESCALATE

    if view.slot_balances.get(w.slot, 0) < w.amount:
        # With matching precondition hash, insufficient balance means the issuer
        # misrepresented the slot state at that epoch: genuine misbehavior.
        raise WarrantApplicabilityError(
            f"precondition hash matched but slot {w.slot} balance "
            f"{view.slot_balances.get(w.slot, 0)} < {w.amount} for warrant from {w.issuer}"
        )

    return Verdict.APPLY


def apply_warrant(w: Warrant, view: LedgerView) -> None:
    verdict = classify_warrant(w, view)
    if verdict is Verdict.DEFER:
        raise WarrantApplicabilityError(
            f"cannot apply deferred warrant for {w.worker}@{w.epoch_boundary}; "
            f"head_epoch={view.head_epoch}"
        )
    if verdict is Verdict.ESCALATE:
        raise WarrantApplicabilityError(
            f"warrant from {w.issuer} for {w.worker}/{w.slot}@{w.epoch_boundary} "
            f"requires conflict resolution: precondition hash diverged from local replica"
        )
    key = (w.worker, w.slot, w.epoch_boundary)
    if key in view.applied_warrants:
        return
    view.slot_balances[w.slot] = view.slot_balances.get(w.slot, 0) - w.amount
    view.applied_warrants.add(key)
