# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-attestation-window-skew-when-a-federated-peer-s-capability-token-expires-mid-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-attestation-window-skew-when-a-federated-peer-s-capability-token-expires-mid-delegation.warrant.json
# Markdown SHA-256:   0904c5896703ead4c08fa825b07777e14019efac130f306c0c43d5d43ba0edc9
# Code AST SHA-256:   8174a6ebc1a43b14ffb6663db205ec4bbc91c5ec6fcf7e10d6cd0defe82c91c9
# Verified Classes:   AttestationWindowSkewError, Warrant, GatewayPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AttestationWindowSkewError(RuntimeError):
    """Raised when a warrant is valid by issuer/holder clocks but violates a
    downstream gateway's undiscoverable freshness floor mid-delegation."""
    pass


@dataclass
class Warrant:
    iat: float
    nbf: float
    exp: float


@dataclass
class GatewayPolicy:
    freshness_floor_s: float
    # None means the floor is NOT published in the capability descriptor.
    advertised: bool


def should_inherit(warrant: Warrant, now: float, latency_p99: float,
                   floor_min: float | None) -> bool:
    """Decide whether to pass the parent warrant down the chain or re-mint.

    Re-mint is the safe default when the floor is unknown: inheritance under an
    undiscoverable floor cannot be proven safe, so it must not be assumed.
    """
    age = now - warrant.iat
    if floor_min is None:
        return False  # unknown floor -> re-mint
    return (age + latency_p99) < floor_min


def delegate(warrant: Warrant, now: float, latency_p99: float,
             policy: GatewayPolicy) -> Warrant:
    floor = policy.freshness_floor_s if policy.advertised else None
    if should_inherit(warrant, now, latency_p99, floor):
        return warrant
    if not policy.advertised:
        # We re-mint, but the caller must know the floor was a guess.
        raise AttestationWindowSkewError(
            f"gateway freshness_floor={policy.freshness_floor_s}s is not "
            f"advertised in capability descriptor; warrant age="
            f"{now - warrant.iat:.1f}s cannot be bounded against it. "
            f"Re-mint required and policy must be published."
        )
    return Warrant(iat=now, nbf=now, exp=now + (warrant.exp - warrant.nbf))


def present(warrant: Warrant, now: float, policy: GatewayPolicy) -> None:
    if now - warrant.iat > policy.freshness_floor_s:
        raise AttestationWindowSkewError(
            f"FRESHNESS_FLOOR_VIOLATION: age={now - warrant.iat:.1f}s > "
            f"floor={policy.freshness_floor_s}s; terminal, do not retry"
        )
