# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-delegated-aaif-credential-expiry-from-upstream-revocation-during-cross-realm-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-delegated-aaif-credential-expiry-from-upstream-revocation-during-cross-realm-exchange.warrant.json
# Markdown SHA-256:   ce3240fbd2c65a3ae6ae64684b28a6b427ec09b08f95d5531de3f445a3fc80c7
# Code AST SHA-256:   2f4f8267ae51464dbf93bf0f2501b6bc39bb4a147d44d8fcfa7115425a97f857
# Verified Classes:   AmbiguousRevocationSignal
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class AmbiguousRevocationSignal(RuntimeError):
    """Raised when an AAIF introspection response cannot distinguish
    lease expiry from root revocation, making re-delegation unsafe."""
    pass


RE_DELEGATION_SAFE_REASONS = frozenset({"expired", "superseded"})


def classify_and_maybe_redelegate(
    introspection: dict,
    intermediate_root_checked_at: float,
    now: float,
    root_check_ttl: float,
    revocation_sync_window: float,
    delegated_lease: float,
) -> str:
    """Return 're-delegate' or 'escalate'. Never silently retries on ambiguity."""
    if introspection.get("active"):
        return "valid"

    reason = introspection.get("revocation_reason")
    if reason is None:
        raise AmbiguousRevocationSignal(
            "introspection returned active:false with no revocation_reason; "
            "cannot distinguish lease expiry from root revocation"
        )

    root_fresh = (now - intermediate_root_checked_at) < root_check_ttl
    sync_ok = revocation_sync_window < delegated_lease

    if reason in RE_DELEGATION_SAFE_REASONS and root_fresh and sync_ok:
        return "re-delegate"

    if reason == "revoked" or not root_fresh:
        raise AmbiguousRevocationSignal(
            f"re-delegation blocked: reason={reason!r}, root_fresh={root_fresh}, "
            f"sync_ok={sync_ok}; treating as terminal to prevent confused-deputy escalation"
        )

    return "escalate"
