# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-aaif-agent-passport-when-the-workload-bound-credential-s-attestation-quote-is-valid-but-its-bou.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-aaif-agent-passport-when-the-workload-bound-credential-s-attestation-quote-is-valid-but-its-bou.warrant.json
# Markdown SHA-256:   3324f4ac1f47eb04450094479d26c1244de9ec6966e8b736489ec816bafa7532
# Code AST SHA-256:   c652d4befe9c3a323088ffebb4efea869fbd2a1ed0c32791cb43bde90cd50e7d
# Verified Classes:   StaleWorkloadBindingError, Passport, LiveAttestation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleWorkloadBindingError(RuntimeError):
    """Raised when a passport's workload measurement cannot be shown to match
    the live peer, so the binding is stale and policy-gated routing is unsafe."""
    pass


@dataclass
class Passport:
    agent_id: str
    issuer_sig_valid: bool
    quote_nonce: bytes
    quote_valid: bool
    workload_measurement: str
    measurement_epoch: int


@dataclass
class LiveAttestation:
    # Obtained from the peer over the verifier's nonce, independent of the passport.
    nonce: bytes
    measurement: str
    measurement_epoch: int
    signature_valid: bool


def verify_handshake(
    passport: Passport,
    verifier_nonce: bytes,
    live: LiveAttestation | None,
    policy_requires_current_binding: bool,
) -> str:
    if not passport.issuer_sig_valid:
        raise StaleWorkloadBindingError("issuer signature invalid; cannot establish endorsement")
    if passport.quote_nonce != verifier_nonce or not passport.quote_valid:
        raise StaleWorkloadBindingError("quote nonce mismatch or invalid; replay suspected")

    if live is None:
        # No live challenge possible: endorsement holds, currency does not.
        if policy_requires_current_binding:
            raise StaleWorkloadBindingError(
                "policy requires current workload binding but peer produced no live attestation"
            )
        return "ACCEPT_STALE"

    if live.nonce != verifier_nonce or not live.signature_valid:
        raise StaleWorkloadBindingError("live attestation nonce/signature invalid")

    if live.measurement != passport.workload_measurement:
        raise StaleWorkloadBindingError(
            f"workload divergence: passport={passport.workload_measurement} "
            f"live={live.measurement} epoch_passport={passport.measurement_epoch} "
            f"epoch_live={live.measurement_epoch}"
        )

    if live.measurement_epoch < passport.measurement_epoch:
        raise StaleWorkloadBindingError("live measurement epoch older than passport; rollback suspected")

    return "ACCEPT_CURRENT"
