# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-renew-a-hardware-attested-agent-identity-token-the-signer-clock-vs-token-nbf-skew-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-renew-a-hardware-attested-agent-identity-token-the-signer-clock-vs-token-nbf-skew-boundary.warrant.json
# Markdown SHA-256:   0cc2f6ef34a43b6170b9eb1614bfc4936f501c7f4532cddf01efcf2a2b035404
# Code AST SHA-256:   5f1a45a370654b2bc02c828f0988e01e9e7ce6279fbc72d655501bbd5aacebef
# Verified Classes:   AttestationRenewalError, Token, RenewalDecision
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AttestationRenewalError(RuntimeError):
    """Raised when a hardware-attested token renewal violates a boundary invariant."""
    pass


@dataclass
class Token:
    nbf: float          # not-before, seconds, signer clock
    exp: float          # expiry, seconds, signer clock
    hardware_bound: bool
    nonce_fresh: bool
    token_id: str


@dataclass
class RenewalDecision:
    action: str         # "use_now" | "schedule_at" | "refuse_fail_closed" | "re_attest"
    wake_at: float | None = None
    reason: str = ""


def decide_renewal(
    current: Token,
    candidate: Token,
    verifier_now: float,
    measured_skew_s: float,
    token_lifetime_s: float,
) -> RenewalDecision:
    # Invariant 1: attestation must be hardware-bound and nonce-fresh.
    if not candidate.hardware_bound or not candidate.nonce_fresh:
        raise AttestationRenewalError(
            f"token {candidate.token_id} lacks hardware binding or fresh nonce; "
            "cannot apply skew tolerance"
        )

    # Invariant 2: renewal without re-attestation must not go backward in nbf.
    if candidate.nbf < current.nbf:
        raise AttestationRenewalError(
            f"monotonicity violation: candidate nbf {candidate.nbf:.3f} < "
            f"current nbf {current.nbf:.3f} for token {candidate.token_id}; "
            "require full re-attestation with fresh nonce"
        )

    tolerance = min(measured_skew_s, token_lifetime_s / 10.0)
    early_by = candidate.nbf - verifier_now

    if verifier_now >= candidate.exp:
        return RenewalDecision("re_attest", reason="candidate already expired")

    if early_by <= tolerance:
        return RenewalDecision("use_now", reason=f"within tolerance ({early_by:.3f}s)")

    if early_by <= measured_skew_s:
        # Valid but early: schedule a single wake, do NOT retry-storm.
        return RenewalDecision(
            "schedule_at",
            wake_at=candidate.nbf + 0.001,
            reason=f"early by {early_by:.3f}s within measured skew {measured_skew_s:.3f}s",
        )

    # Early beyond measurable skew: signer fault, not workload fault.
    raise AttestationRenewalError(
        f"signer produced token {candidate.token_id} with nbf {early_by:.3f}s "
        f"ahead of verifier, exceeding measured skew {measured_skew_s:.3f}s; "
        "refuse renewal and alert signer owner"
    )


def renewal_loop(
    current: Token,
    mint_fn,
    verifier_now_fn,
    measured_skew_s: float,
    token_lifetime_s: float,
    max_cycles: int = 5,
):
    for _ in range(max_cycles):
        candidate = mint_fn()
        now = verifier_now_fn()
        decision = decide_renewal(
            current, candidate, now, measured_skew_s, token_lifetime_s
        )
        if decision.action == "use_now":
            return candidate
        if decision.action == "schedule_at":
            sleep_for = max(0.0, decision.wake_at - now)
            time.sleep(sleep_for)
            # Re-verify the same candidate after the scheduled wake.
            if verifier_now_fn() >= candidate.nbf:
                return candidate
            raise AttestationRenewalError(
                f"candidate {candidate.token_id} still early after scheduled wake; "
                "clock estimate is unreliable"
            )
        if decision.action == "re_attest":
            raise AttestationRenewalError(
                f"candidate {candidate.token_id} expired; full re-attestation required"
            )
    raise AttestationRenewalError("renewal loop exhausted without a usable token")
