# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-escrow-release-divergence-when-a-settlement-rail-s-dispute-window-outlives-the-committing-agent-s-context-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-escrow-release-divergence-when-a-settlement-rail-s-dispute-window-outlives-the-committing-agent-s-context-horizon.warrant.json
# Markdown SHA-256:   7d3518e8cb421b6d7e7753d4fc4ad2fa94db29952572be3cc8999e0505b5f10d
# Code AST SHA-256:   83c394d8134d799d8d2984e215a7f88699c834061e502b497e3adedcbda6f4d4
# Verified Classes:   EscrowState, EscrowDivergenceError, Commitment, RailView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from enum import Enum


class EscrowState(Enum):
    PENDING_RELEASE = "pending_release"
    DISPUTE_OPEN = "dispute_open"
    RESOLVED = "resolved"
    DEFAULTED = "defaulted"


class EscrowDivergenceError(RuntimeError):
    """Raised when a committing instance attempts to mutate an escrow whose
    authoritative rail state no longer matches its reconstructed commitment."""


@dataclass(frozen=True)
class Commitment:
    nonce: str
    state_hash: str
    dispute_deadline: float  # epoch seconds, from rail at commit time
    verifier_id: str


@dataclass(frozen=True)
class RailView:
    state: EscrowState
    state_hash: str
    dispute_deadline: float


def reconcile_before_release(
    commitment: Commitment,
    rail_view: RailView,
    now: float,
) -> None:
    """Gate every escrow-mutating call on a fresh rail read.

    Invariant: a release may proceed only if the rail confirms the nonce still
    addresses a PENDING_RELEASE escrow, the state hash matches the persisted
    commitment, and the dispute deadline has not passed.
    """
    if rail_view.state_hash != commitment.state_hash:
        raise EscrowDivergenceError(
            f"state_hash mismatch: commitment={commitment.state_hash} "
            f"rail={rail_view.state_hash}; reconstructed nonce is stale"
        )

    if rail_view.state is EscrowState.DISPUTE_OPEN:
        raise EscrowDivergenceError(
            f"escrow {commitment.nonce} is under dispute; release path is "
            f"invalid until dispute resolution. deadline={rail_view.dispute_deadline}"
        )

    if rail_view.state is not EscrowState.PENDING_RELEASE:
        raise EscrowDivergenceError(
            f"escrow {commitment.nonce} in terminal state {rail_view.state.value}; "
            f"no release permitted"
        )

    if now >= commitment.dispute_deadline:
        raise EscrowDivergenceError(
            f"dispute deadline {commitment.dispute_deadline} passed at {now}; "
            f"escrow is eligible for default resolution, not release"
        )
