# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-did-passport-whose-delegation-chain-spans-two-trust-domains-with-non-overlapping-revocation-registries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-did-passport-whose-delegation-chain-spans-two-trust-domains-with-non-overlapping-revocation-registries.warrant.json
# Markdown SHA-256:   3b0ddd61a45c5e45caf5f2aa8f986e256ffb7ff228fdad44de98ace9a0a5cc21
# Code AST SHA-256:   6f4f684db4b464369b8107a2af3ab30af518f4ef31a58c28aed229571d004b83
# Verified Classes:   ChainAttestationError, Hop, LeafCredential
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ChainAttestationError(RuntimeError):
    """Raised when a delegation chain cannot be validated under the
    per-hop authoritative status invariant."""
    pass


@dataclass
class Hop:
    issuer_did: str
    domain: str
    status_bit: Optional[int]      # None => registry unreachable
    registry_snapshot_time: Optional[float]
    registry_ttl: float


@dataclass
class LeafCredential:
    issuer_did: str
    exp: float
    chain_attestation: Optional[dict]  # {attested_at, max_age, hop_statuses}


def validate_chain(leaf: LeafCredential, hops: list[Hop], now: float,
                   require_attestation: bool = True) -> bool:
    # Rule 1: every hop must be checked against its authoritative registry.
    for i, hop in enumerate(hops):
        if hop.status_bit is None:
            raise ChainAttestationError(
                f"hop {i} ({hop.issuer_did}@{hop.domain}): registry unreachable; "
                f"fail-closed required, cannot assert validity"
            )
        if hop.status_bit != 0:
            raise ChainAttestationError(
                f"hop {i} ({hop.issuer_did}@{hop.domain}): revoked (status_bit=1)"
            )
        # Rule 2: cache age folds into effective expiry.
        if hop.registry_snapshot_time is not None:
            effective_exp = min(leaf.exp, hop.registry_snapshot_time + hop.registry_ttl)
            if now > effective_exp:
                raise ChainAttestationError(
                    f"hop {i}: cached registry snapshot stale "
                    f"(now={now:.0f} > effective_exp={effective_exp:.0f})"
                )

    # Rule 3: leaf must carry a fresh whole-chain attestation.
    if require_attestation:
        att = leaf.chain_attestation
        if att is None:
            raise ChainAttestationError(
                "leaf credential lacks chainAttestation; verifier cannot "
                "assert ancestor status without trusting an unreachable registry"
            )
        if att["attested_at"] + att["max_age"] < now:
            raise ChainAttestationError(
                f"chainAttestation stale: attested_at+max_age="
                f"{att['attested_at'] + att['max_age']:.0f} < now={now:.0f}"
            )
        if any(s != 0 for s in att["hop_statuses"]):
            raise ChainAttestationError(
                "chainAttestation reports a revoked ancestor hop"
            )

    return True
