# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-verify-a-delegated-credential-chain-when-an-intermediate-issuer-s-revocation-status-is-only-knowable-through.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-verify-a-delegated-credential-chain-when-an-intermediate-issuer-s-revocation-status-is-only-knowable-through.warrant.json
# Markdown SHA-256:   9a9e717870e565092350a713d881aa74470a575d549c0a410e061716950ca203
# Code AST SHA-256:   2a29c70ba3c19fc83807254782873b8baadd66414cc8d61df3565d507cb00283
# Verified Classes:   DelegatedChainStatusError, Hop, ChainVerdict
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class DelegatedChainStatusError(RuntimeError):
    """Raised when a delegated credential chain cannot be proven currently authorized."""


@dataclass
class Hop:
    hop_id: str
    status_list_ttl: int          # seconds the issuing party promises freshness
    last_confirmed_negative: Optional[float] = None  # monotonic timestamp
    reachable: bool = False
    revoked: bool = False


@dataclass
class ChainVerdict:
    valid: bool
    reason: str
    degraded_hops: list = field(default_factory=list)


def evaluate_chain(chain: list[Hop], now: Optional[float] = None) -> ChainVerdict:
    """Chain-scoped authorization verdict.

    Invariant: verdict is VALID only if every hop is reachable, fresh within the
    minimum status TTL across the chain, and negative for revocation. Unreachability
    or staleness on any hop yields UNKNOWN (valid=False), never fail-open.
    """
    now = now if now is not None else time.monotonic()

    if not chain:
        raise DelegatedChainStatusError("empty delegated chain: no authority to evaluate")

    min_ttl = min(h.status_list_ttl for h in chain)
    degraded = []

    for hop in chain:
        if hop.revoked:
            raise DelegatedChainStatusError(
                f"hop {hop.hop_id} is revoked; purge cached verdict and deny action"
            )
        if not hop.reachable:
            degraded.append(hop.hop_id)
            continue
        if hop.last_confirmed_negative is None:
            degraded.append(hop.hop_id)
            continue
        age = now - hop.last_confirmed_negative
        if age >= min_ttl:
            degraded.append(hop.hop_id)

    if degraded:
        # Unknown authority on any hop must NOT be collapsed into "valid".
        return ChainVerdict(
            valid=False,
            reason=(
                "authorization UNKNOWN: unreachable or stale status on "
                f"{degraded}; unreachability is not authorization"
            ),
            degraded_hops=degraded,
        )

    return ChainVerdict(valid=True, reason="all hops reachable, fresh, negative")


def require_authorized(chain: list[Hop], now: Optional[float] = None) -> None:
    verdict = evaluate_chain(chain, now=now)
    if not verdict.valid:
        raise DelegatedChainStatusError(
            f"refusing privileged action: {verdict.reason}"
        )


if __name__ == "__main__":
    # Hop 2's status channel went dark after its window lapsed.
    chain = [
        Hop("root", status_list_ttl=600, last_confirmed_negative=time.monotonic()),
        Hop("org-issuer", status_list_ttl=600, last_confirmed_negative=time.monotonic() - 1200,
            reachable=False),
        Hop("team-issuer", status_list_ttl=600, last_confirmed_negative=time.monotonic()),
    ]
    require_authorized(chain)  # raises DelegatedChainStatusError, does not fail open
