# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-agent-credential-during-cross-org-trust-bootstrap-when-the-revocation-list-is-fresher-than-the-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-agent-credential-during-cross-org-trust-bootstrap-when-the-revocation-list-is-fresher-than-the-delegation-chain.warrant.json
# Markdown SHA-256:   72f0929f641506c5b5f542ce8a82c5485c32126567b78440a2f0bb0df826e75f
# Code AST SHA-256:   42cc201362938da429d4a3d2fbdc90c649255ec56b045414872941106d28e3f0
# Verified Classes:   StaleStatusBootstrapError, Link, StatusList
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleStatusBootstrapError(RuntimeError):
    """Raised when a status artifact cannot prove non-revocation for a chain link."""
    pass


@dataclass
class Link:
    link_id: str
    nbf: float          # not-before (issuance epoch)
    exp: float          # expiry epoch
    signature_ok: bool


@dataclass
class StatusList:
    this_update: float  # when this list was cut
    next_update: float  # declared freshness horizon
    revoked_ids: set


def admit_chain(chain: list[Link], status: StatusList, now: float,
                refetch_hook=None) -> bool:
    # Step 1: structural + signature + expiry checks (the easy booleans).
    for link in chain:
        if not link.signature_ok:
            raise StaleStatusBootstrapError(
                f"link {link.link_id}: bad signature")
        if not (link.nbf <= now <= link.exp):
            raise StaleStatusBootstrapError(
                f"link {link.link_id}: outside validity window")

    # Step 2: the invariant everyone misses.
    chain_floor = max(link.nbf for link in chain)
    if status.this_update < chain_floor:
        # The status list predates at least one link's issuance; it cannot
        # reflect a revocation of an ancestor that occurred after that link
        # was minted. Force a synchronous re-fetch, bypassing cache.
        if refetch_hook is None:
            raise StaleStatusBootstrapError(
                f"status.thisUpdate={status.this_update} < chain_floor="
                f"{chain_floor}; cannot prove non-revocation, no refetch path")
        status = refetch_hook(min_this_update=chain_floor)
        if status.this_update < chain_floor:
            raise StaleStatusBootstrapError(
                f"refetched status still stale: thisUpdate="
                f"{status.this_update} < chain_floor={chain_floor}")

    # Step 3: check EVERY link, not just the leaf.
    for link in chain:
        if link.link_id in status.revoked_ids:
            raise StaleStatusBootstrapError(
                f"link {link.link_id} revoked as of {status.this_update}")

    # Step 4: descendant-issuance rule — an ancestor revoked after a
    # descendant was issued retroactively taints the descendant.
    for i in range(len(chain) - 1):
        ancestor = chain[i]
        descendant = chain[i + 1]
        if ancestor.link_id in status.revoked_ids:
            if status.this_update > descendant.nbf:
                raise StaleStatusBootstrapError(
                    f"ancestor {ancestor.link_id} revoked at "
                    f"{status.this_update} after descendant "
                    f"{descendant.link_id} issued at {descendant.nbf}")

    return True
