# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attests-a-peer-s-identity-before-its-own-warrant-chain-has-been-anchored-trust-bootstrap-ordering-failures-in-cross-org.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attests-a-peer-s-identity-before-its-own-warrant-chain-has-been-anchored-trust-bootstrap-ordering-failures-in-cross-org.warrant.json
# Markdown SHA-256:   5225c6680cf4a8b4ee5c1eabd7876a7efaedfe3b94572fda470b65497d7cd0ab
# Code AST SHA-256:   df5e7003b19549110afdd1d46f1b2e9bf77261b267a397d00708b68acc16c629
# Verified Classes:   HandshakePhase, StaleSelfAnchorError, AnchorState, PeerPreamble
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class HandshakePhase(Enum):
    PREAMBLE = "preamble"
    SELF_ANCHOR = "self_anchor"
    VERIFY_PEER = "verify_peer"
    ASSERT_SELF = "assert_self"
    COMPLETE = "complete"


class StaleSelfAnchorError(RuntimeError):
    """Raised when an instance attempts to emit its outbound attestation
    while its own warrant chain is anchored to a root epoch the peer
    will not accept. This is an emitter-side ordering fault, not a
    receiver-side rejection: the emitter must not construct the frame."""


@dataclass
class AnchorState:
    epoch: int
    root_published_at: int  # monotonic hours
    refreshed: bool


@dataclass
class PeerPreamble:
    peer_id: str
    min_acceptable_epoch: int


def run_handshake(
    self_anchor: AnchorState,
    peer_preamble: PeerPreamble,
    peer_verified: bool,
    now_hours: int,
) -> HandshakePhase:
    # Correct partial order: exchange preamble BEFORE asserting.
    # The emitter learns the peer's acceptance window first.
    if peer_preamble.min_acceptable_epoch <= 0:
        raise StaleSelfAnchorError(
            f"peer {peer_preamble.peer_id} advertised invalid acceptance window"
        )

    # Inbound verification may have succeeded, but that is NOT evidence
    # that our own warrant is acceptable to the peer. Gate on self-anchor.
    if not peer_verified:
        return HandshakePhase.VERIFY_PEER

    # Synchronous self-anchor gate: must satisfy the peer's window.
    if not self_anchor.refreshed:
        raise StaleSelfAnchorError(
            f"self anchor epoch {self_anchor.epoch} not refreshed; "
            f"cannot assert to peer {peer_preamble.peer_id}"
        )

    if self_anchor.epoch < peer_preamble.min_acceptable_epoch:
        raise StaleSelfAnchorError(
            f"self anchor epoch {self_anchor.epoch} < peer "
            f"{peer_preamble.peer_id} min_acceptable_epoch "
            f"{peer_preamble.min_acceptable_epoch}; refusing to emit "
            f"outbound attestation (would be rejected, producing "
            f"asymmetric split-brain trust state)"
        )

    # Only now may we construct and emit the outbound attestation.
    return HandshakePhase.ASSERT_SELF
