# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-aaif-credential-as-invalid-at-the-moment-of-tool-invocation-rather-than-at-issuance.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-aaif-credential-as-invalid-at-the-moment-of-tool-invocation-rather-than-at-issuance.warrant.json
# Markdown SHA-256:   b4977d4ebb591a410ca6c62939d325d2da142ca884465477c4d2c027eac664bc
# Code AST SHA-256:   9b89c3e098bc41fb1aa5ed610e07ce8e154c1efc4f94a605d85c1dd420fe6dac
# Verified Classes:   DelegationPathInvalid, RevocationStale, Credential, CachedAuthority
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class DelegationPathInvalid(RuntimeError):
    """Raised when a delegated AAIF credential fails invocation-time path validation."""
    pass


class RevocationStale(DelegationPathInvalid):
    """Revocation state is older than the configured staleness bound."""
    pass


@dataclass
class Credential:
    subject: str
    delegator: Optional[str]
    scope: frozenset
    aud: str
    nbf: float
    exp: float
    revoked: bool = False


@dataclass
class CachedAuthority:
    effective_scope: frozenset
    verified_at: float
    revocation_epoch: float
    path_ids: tuple = field(default_factory=tuple)


CLOCK_SKEW_TOLERANCE = 120.0
MAX_REVOCATION_STALENESS_WRITE = 30.0


def _now() -> float:
    return time.time()


def verify_delegation_path(
    leaf: Credential,
    parents: list,
    requested_op: str,
    requested_scope: str,
    endpoint_aud: str,
    last_revocation_refresh: float,
    cached: Optional[CachedAuthority] = None,
) -> CachedAuthority:
    now = _now()

    if cached is not None and (now - cached.verified_at) <= MAX_REVOCATION_STALENESS_WRITE:
        if requested_scope not in cached.effective_scope:
            raise DelegationPathInvalid(
                f"op {requested_op!r} requires {requested_scope!r} "
                f"not in cached effective scope {sorted(cached.effective_scope)}"
            )
        return cached

    if (now - last_revocation_refresh) > MAX_REVOCATION_STALENESS_WRITE:
        raise RevocationStale(
            f"revocation state age {now - last_revocation_refresh:.1f}s exceeds "
            f"{MAX_REVOCATION_STALENESS_WRITE}s bound; refusing to admit {requested_op!r}"
        )

    full_path = list(parents) + [leaf]
    for cred in full_path:
        if cred.nbf - CLOCK_SKEW_TOLERANCE > now:
            raise DelegationPathInvalid(
                f"credential for {cred.subject} not yet valid (nbf={cred.nbf:.0f}, now={now:.0f})"
            )
        if cred.exp + CLOCK_SKEW_TOLERANCE < now:
            raise DelegationPathInvalid(
                f"credential for {cred.subject} expired (exp={cred.exp:.0f}, now={now:.0f})"
            )
        if cred.revoked:
            raise DelegationPathInvalid(
                f"credential for {cred.subject} is revoked; path severed"
            )

    if leaf.aud != endpoint_aud:
        raise DelegationPathInvalid(
            f"audience mismatch: leaf aud={leaf.aud!r} endpoint={endpoint_aud!r}"
        )

    effective = frozenset.intersection(*[c.scope for c in full_path])
    if requested_scope not in effective:
        raise DelegationPathInvalid(
            f"requested {requested_scope!r} not in path-intersected scope "
            f"{sorted(effective)}; leaf declared {sorted(leaf.scope)}"
        )

    return CachedAuthority(
        effective_scope=effective,
        verified_at=now,
        revocation_epoch=last_revocation_refresh,
        path_ids=tuple(c.subject for c in full_path),
    )
