# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-a-delegated-scope-token-after-an-aaif-credential-rotation-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-a-delegated-scope-token-after-an-aaif-credential-rotation-mid-handoff.warrant.json
# Markdown SHA-256:   4d59b320c5f49412a3d96564da55e49cbc9185955c63611e65b8461acecf2785
# Code AST SHA-256:   e544f1fc178a03e890a8402fcc0c83b6dfd306746deb3b7b158aa398afdf8c04
# Verified Classes:   OrphanedWarrantError, StaleMintError, TrustBundle, DST, AAIFClient
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class OrphanedWarrantError(RuntimeError):
    """Raised when a delegated-scope token's signing key is not live in the current trust bundle."""


class StaleMintError(RuntimeError):
    """Raised when an agent attempts to mint a child DST from unrefreshed key material."""


@dataclass
class TrustBundle:
    live_keys: set
    fetched_at: float

    def has(self, key_id: str) -> bool:
        return key_id in self.live_keys


@dataclass
class DST:
    subject: str
    scopes: set
    signing_key_id: str
    parent_ref: str
    chain_depth: int
    exp: float
    minted_at: float = field(default_factory=time.time)


class AAIFClient:
    def __init__(self, agent_id, bundle_ttl=900.0, grace_window=300.0):
        self.agent_id = agent_id
        self.bundle_ttl = bundle_ttl
        self.grace_window = grace_window
        self._bundle = None
        self._bundle_fetched = 0.0

    def _bundle_is_fresh(self) -> bool:
        return (time.time() - self._bundle_fetched) < self.bundle_ttl

    def refresh_bundle(self, authority) -> TrustBundle:
        self._bundle = authority.current_bundle()
        self._bundle_fetched = time.time()
        return self._bundle

    def verify(self, dst: DST, authority) -> bool:
        if not self._bundle_is_fresh():
            self.refresh_bundle(authority)
        if time.time() > dst.exp:
            return False
        if not self._bundle.has(dst.signing_key_id):
            raise OrphanedWarrantError(
                f"DST for {dst.subject} signed by {dst.signing_key_id}, "
                f"not in live bundle at depth {dst.chain_depth}"
            )
        if dst.chain_depth >= 2 and not authority.parent_is_live(dst.parent_ref):
            raise OrphanedWarrantError(
                f"parent warrant {dst.parent_ref} revoked or rotated"
            )
        return True

    def mint_child(self, parent: DST, subject: str, scopes: set, authority) -> DST:
        # The mint-time guard: refresh BEFORE signing, never mint from cache.
        # This is the invariant that the trace above violated.
        if not self._bundle_is_fresh():
            self.refresh_bundle(authority)
        if not self._bundle.has(parent.signing_key_id):
            raise StaleMintError(
                f"refusing to mint child DST for {subject}: parent key "
                f"{parent.signing_key_id} no longer live; re-derive parent first"
            )
        if not scopes.issubset(parent.scopes):
            raise StaleMintError(
                f"scope escalation: {scopes - parent.scopes} not held by parent"
            )
        child_depth = parent.chain_depth + 1
        # Cap lifetime at depth >= 2 to the rotation period so revocation
        # cannot be outlived by more than one cycle.
        max_life = min(parent.exp - time.time(), self.grace_window)
        return DST(
            subject=subject,
            scopes=scopes,
            signing_key_id=parent.signing_key_id,
            parent_ref=hashlib.sha256(
                f"{parent.subject}:{parent.minted_at}".encode()
            ).hexdigest()[:16],
            chain_depth=child_depth,
            exp=time.time() + max_life,
        )
