# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-delegated-aaif-credential-outlived-the-attestation-it-was-bound-to.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-delegated-aaif-credential-outlived-the-attestation-it-was-bound-to.warrant.json
# Markdown SHA-256:   ee6a0580caaca7e84aa8ba3c9df0f9c441d94c044fa53bb46be3e30596cdf1df
# Code AST SHA-256:   e9d98c3cd7e8d7c617e165881ef0a961a8c3af9bd883bb4b532da0e9c64a6ac1
# Verified Classes:   AttestationDecoupledError, Attestation, DelegatedCredential
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AttestationDecoupledError(RuntimeError):
    """Raised when a delegated credential's attestation is no longer current
    and the delegation is outside the grace horizon."""


@dataclass(frozen=True)
class Attestation:
    ref: str
    status: str            # "current" | "superseded" | "revoked"
    superseded_at: float | None


@dataclass(frozen=True)
class DelegatedCredential:
    attestation_ref: str
    issued_at: float
    not_after: float
    signature_valid: bool


GRACE_HORIZON_S = 60.0


def verify_delegation(
    cred: DelegatedCredential,
    resolve_attestation,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    if not cred.signature_valid:
        raise AttestationDecoupledError("credential signature chain does not verify")
    if now >= cred.not_after:
        raise AttestationDecoupledError("credential expired (clean failure)")

    att: Attestation | None = resolve_attestation(cred.attestation_ref)
    if att is None:
        raise AttestationDecoupledError(
            f"attestation {cred.attestation_ref} unresolvable"
        )

    if att.status == "current":
        return

    if att.status == "revoked":
        raise AttestationDecoupledError(
            f"attestation {att.ref} revoked; delegation void immediately"
        )

    # status == "superseded": apply bounded grace, anchored to issued_at
    if att.superseded_at is None:
        raise AttestationDecoupledError(
            f"attestation {att.ref} superseded without timestamp; unverifiable"
        )
    if cred.issued_at > att.superseded_at:
        # credential minted after supersession is itself suspect
        raise AttestationDecoupledError(
            f"credential issued after attestation {att.ref} superseded"
        )
    if now - att.superseded_at > GRACE_HORIZON_S:
        raise AttestationDecoupledError(
            f"attestation {att.ref} superseded {now - att.superseded_at:.1f}s ago, "
            f"exceeds grace horizon {GRACE_HORIZON_S}s; re-delegation required"
        )
    # within grace: admissible, but caller should request re-delegation
