# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-delegation-credential-mid-chain-when-the-revocation-event-lands-between-its-last-warrant-check-and-the-next-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-delegation-credential-mid-chain-when-the-revocation-event-lands-between-its-last-warrant-check-and-the-next-tool.warrant.json
# Markdown SHA-256:   17b0ba2408c129b0c5620464dd34d52424932466603eee963d8dd8b541a45a1e
# Code AST SHA-256:   b6beb4b4de37cdb3fabf2d8feddc23d0b2227b13354f71cfd646bbb6f881e882
# Verified Classes:   StaleRevocationAssertion, RevocationHandle, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StaleRevocationAssertion(RuntimeError):
    """Raised when a warrant asserts parent validity without a fresh revocation dereference."""
    pass


@dataclass
class RevocationHandle:
    handle_id: str
    revoked: bool = False
    last_deref_at: Optional[float] = None

    def dereference(self, rdp_client) -> bool:
        # RDP = revocation distribution point; must be authoritative, not cached
        self.revoked = rdp_client.is_revoked(self.handle_id)
        self.last_deref_at = time.monotonic()
        return self.revoked


@dataclass
class Warrant:
    warrant_id: str
    scope: str
    issuer: str
    subject: str
    expiry: float                     # monotonic deadline
    parent_handle: Optional[RevocationHandle] = None
    parent_status_claim: Optional[str] = None
    derived_at: Optional[float] = None


def derive_child_warrant(
    parent: Warrant,
    child_scope: str,
    subject: str,
    rdp_client,
    freshness_window_delta: float,
    now: Optional[float] = None,
) -> Warrant:
    """
    Mint a child warrant only if the parent's revocation status is fresh AND
    the freshness window is strictly smaller than the parent's remaining TTL.
    """
    now = time.monotonic() if now is None else now

    if parent.parent_handle is None:
        # Root warrant: no upstream handle to check, but TTL must still hold.
        if now >= parent.expiry:
            raise StaleRevocationAssertion(
                f"root warrant {parent.warrant_id} already expired at derivation"
            )
        return Warrant(
            warrant_id=f"{parent.warrant_id}.child",
            scope=child_scope,
            issuer=parent.subject,
            subject=subject,
            expiry=min(parent.expiry, now + freshness_window_delta),
            parent_status_claim="ROOT",
            derived_at=now,
        )

    handle = parent.parent_handle
    handle.dereference(rdp_client)

    if handle.revoked:
        raise StaleRevocationAssertion(
            f"parent warrant {parent.warrant_id} revoked via handle "
            f"{handle.handle_id}; refusing to derive child scope {child_scope!r}"
        )

    if handle.last_deref_at is None or (now - handle.last_deref_at) >= freshness_window_delta:
        raise StaleRevocationAssertion(
            f"parent revocation handle {handle.handle_id} stale: last deref "
            f"{now - (handle.last_deref_at or 0):.2f}s ago, window {freshness_window_delta}s"
        )

    remaining_parent_ttl = parent.expiry - now
    if freshness_window_delta >= remaining_parent_ttl:
        raise StaleRevocationAssertion(
            f"freshness window {freshness_window_delta}s >= remaining parent TTL "
            f"{remaining_parent_ttl:.2f}s; child could outlive a revocation check"
        )

    return Warrant(
        warrant_id=f"{parent.warrant_id}.child",
        scope=child_scope,
        issuer=parent.subject,
        subject=subject,
        expiry=min(parent.expiry, now + freshness_window_delta),
        parent_handle=handle,
        parent_status_claim="VALID",
        derived_at=now,
    )
