# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-delegated-aaif-attestation-whose-expiry-window-closes-mid-handoff-against-a-downstream-agent-that-has-already-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-delegated-aaif-attestation-whose-expiry-window-closes-mid-handoff-against-a-downstream-agent-that-has-already-cache.warrant.json
# Markdown SHA-256:   faf5e39402857555ee9aef9d26634f67860318cf6170bfdb954d3fa9944ae913
# Code AST SHA-256:   00312e036ebe1f51e36016627f908dac053c29e8d600c8f8b7ed37d45b63b893
# Verified Classes:   StaleDelegationError, Warrant, TrustEntry
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleDelegationError(RuntimeError):
    """Raised when a derived AAIF warrant outlives its backing parent authority."""


@dataclass
class Warrant:
    subject: str
    issuer: str
    not_before: float
    not_after: float
    derived_at: float
    parent_digest: str | None
    signing_key_id: str


@dataclass
class TrustEntry:
    key_id: str
    retired_at: float | None  # None = active
    grace_until: float | None


def derive_child(parent: Warrant, child_subject: str, hop_budget: float,
                 now: float, parent_not_after_cached: float) -> Warrant:
    # Invariant: clamp to the parent's *true* remaining lifetime, not the cached one.
    true_parent_remaining = parent.not_after - now
    if true_parent_remaining <= 0:
        raise StaleDelegationError(
            f"parent {parent.issuer} expired at {parent.not_after}, now={now}"
        )
    effective_budget = min(hop_budget, true_parent_remaining, parent_not_after_cached - now)
    if effective_budget <= 0:
        raise StaleDelegationError(
            f"cached parent window {parent_not_after_cached} already closed at now={now}"
        )
    return Warrant(
        subject=child_subject,
        issuer=parent.subject,
        not_before=now,
        not_after=now + effective_budget,
        derived_at=now,
        parent_digest=f"{parent.subject}:{parent.signing_key_id}",
        signing_key_id=f"{child_subject}-key",
    )


def verify_chain(leaf: Warrant, parents: dict[str, Warrant],
                 trust: dict[str, TrustEntry], now: float) -> None:
    w = leaf
    while w.parent_digest is not None:
        entry = trust.get(w.signing_key_id)
        if entry is None:
            raise StaleDelegationError(f"unknown key {w.signing_key_id}")
        if not (w.not_before <= now <= w.not_after):
            raise StaleDelegationError(f"warrant {w.subject} outside window at {now}")
        parent = parents.get(w.parent_digest)
        if parent is None:
            raise StaleDelegationError(f"missing parent {w.parent_digest}")
        # The boundary: a retired key cannot back a warrant derived after retirement.
        parent_entry = trust.get(parent.signing_key_id)
        if parent_entry is None:
            raise StaleDelegationError(f"unknown parent key {parent.signing_key_id}")
        if parent_entry.retired_at is not None:
            if w.derived_at > parent_entry.retired_at:
                raise StaleDelegationError(
                    f"warrant {w.subject} derived at {w.derived_at} under key "
                    f"{parent.signing_key_id} retired at {parent_entry.retired_at}"
                )
        if w.not_after > parent.not_after:
            raise StaleDelegationError(
                f"derived not_after {w.not_after} exceeds parent {parent.not_after}"
            )
        w = parent
