# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-a-delegated-scope-chain-after-its-issuer-s-revocation-list-goes-stale.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-attests-a-delegated-scope-chain-after-its-issuer-s-revocation-list-goes-stale.warrant.json
# Markdown SHA-256:   9fcdfb0ef1f759ed5abdb85564c31469a4c36ce7d5a599f1be5e2145ef720478
# Code AST SHA-256:   4263df5a57e9bd44b43686deafbae368986b5dcb4bbf5bf97637ea8325575774
# Verified Classes:   StaleRevocationSnapshotError, ScopeAttestation, RevocationSnapshot
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleRevocationSnapshotError(RuntimeError):
    """Raised when a chain hop's issuance postdates the RL snapshot used to clear it."""


@dataclass
class ScopeAttestation:
    issuer: str
    subject: str
    delegated_scope: frozenset
    not_before: float
    not_after: float
    revocation_ref: str


@dataclass
class RevocationSnapshot:
    issuer: str
    fetched_at: float
    revoked_subjects: frozenset = field(default_factory=frozenset)


def verify_delegated_chain(
    chain: list[ScopeAttestation],
    snapshots: dict[str, RevocationSnapshot],
    now: float,
    *,
    allow_indeterminate: bool = False,
) -> bool:
    if not chain:
        raise StaleRevocationSnapshotError("empty chain")

    parent_scope = None
    parent_not_after = None

    for hop in chain:
        # 1. temporal validity of the leaf/hop itself
        if not (hop.not_before <= now <= hop.not_after):
            raise StaleRevocationSnapshotError(
                f"hop {hop.issuer}->{hop.subject} outside validity window"
            )

        # 2. lifetime containment: child must not outlive parent
        if parent_not_after is not None and hop.not_after > parent_not_after:
            raise StaleRevocationSnapshotError(
                f"hop {hop.subject} not_after {hop.not_after} exceeds "
                f"parent not_after {parent_not_after}"
            )

        # 3. scope subset
        if parent_scope is not None and not hop.delegated_scope <= parent_scope:
            raise StaleRevocationSnapshotError(
                f"scope escalation at {hop.subject}: "
                f"{hop.delegated_scope} !<= {parent_scope}"
            )

        # 4. THE BOUNDARY: snapshot must be at least as new as the hop's issuance
        snap = snapshots.get(hop.issuer)
        if snap is None:
            raise StaleRevocationSnapshotError(
                f"no revocation snapshot for issuer {hop.issuer}"
            )
        if snap.fetched_at < hop.not_before:
            # revocation status of this hop is UNKNOWN, not valid
            if not allow_indeterminate:
                raise StaleRevocationSnapshotError(
                    f"snapshot for {hop.issuer} fetched_at={snap.fetched_at} "
                    f"predates hop.not_before={hop.not_before}; "
                    f"revocation state indeterminate -> fail closed"
                )
            return False

        # 5. only now is a "not in RL" clear meaningful
        if hop.subject in snap.revoked_subjects:
            raise StaleRevocationSnapshotError(
                f"hop {hop.subject} revoked per snapshot@{snap.fetched_at}"
            )

        parent_scope = hop.delegated_scope
        parent_not_after = hop.not_after

    return True


def reattest(
    chain: list[ScopeAttestation],
    snapshots: dict[str, RevocationSnapshot],
    now: float,
) -> ScopeAttestation:
    """Re-issue a leaf; must NOT reuse a snapshot older than any hop's issuance."""
    # Force a fresh snapshot requirement by rejecting stale caches outright.
    verify_delegated_chain(chain, snapshots, now, allow_indeterminate=False)
    leaf = chain[-1]
    return ScopeAttestation(
        issuer=leaf.issuer,
        subject=leaf.subject,
        delegated_scope=leaf.delegated_scope,
        not_before=now,
        not_after=min(leaf.not_after, snapshots[leaf.issuer].fetched_at + 3600.0),
        revocation_ref=leaf.revocation_ref,
    )
