# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-outlives-its-own-lease.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-outlives-its-own-lease.warrant.json
# Markdown SHA-256:   06826de4a9a568fecb36dfb3033d5abfbdc36129f100af49c771a5a2afbb55c1
# Code AST SHA-256:   d06305bb41e074d33535b3943edd217fc86a8d57599ebd3ae3457b84a920bca0
# Verified Classes:   DelegationScopeViolation, Lease, DelegatedToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class DelegationScopeViolation(RuntimeError):
    """Raised when a delegated token would outlive its delegator's lease."""
    pass


@dataclass(frozen=True)
class Lease:
    delegator_id: str
    expiry: float  # monotonic seconds
    epoch: int


@dataclass(frozen=True)
class DelegatedToken:
    token_id: str
    delegator_id: str
    scope: str
    not_after: float
    lease_epoch: int


SAFETY_MARGIN_S = 5.0


def issue_delegated_token(
    delegator_id: str,
    scope: str,
    requested_ttl_s: float,
    child_min_window_s: float,
    lease_lookup,
    token_id_factory,
    now: float | None = None,
) -> DelegatedToken:
    now = time.monotonic() if now is None else now

    # Fail closed: if lease state is unreadable, refuse to mint.
    try:
        lease: Lease = lease_lookup(delegator_id)
    except LookupError as exc:
        raise DelegationScopeViolation(
            f"cannot resolve lease for delegator {delegator_id!r}; refusing issuance"
        ) from exc

    lease_remaining = lease.expiry - now - SAFETY_MARGIN_S
    if lease_remaining <= 0:
        raise DelegationScopeViolation(
            f"delegator {delegator_id!r} lease already exhausted "
            f"(remaining={lease_remaining:.1f}s); no authority to delegate"
        )

    # Child needs a window longer than the delegator can authorize:
    # topology is wrong, escalate rather than squeeze.
    if child_min_window_s > lease_remaining:
        raise DelegationScopeViolation(
            f"child requires {child_min_window_s:.1f}s but delegator "
            f"{delegator_id!r} can only authorize {lease_remaining:.1f}s; "
            f"re-issue from a longer-lived principal"
        )

    effective_ttl = min(requested_ttl_s, lease_remaining)
    not_after = now + effective_ttl

    # Invariant guard: never mint a token that outlives the lease.
    if not_after > lease.expiry:
        raise DelegationScopeViolation(
            f"delegated token not_after={not_after:.1f} exceeds "
            f"lease expiry={lease.expiry:.1f} for {delegator_id!r}"
        )

    return DelegatedToken(
        token_id=token_id_factory(),
        delegator_id=delegator_id,
        scope=scope,
        not_after=not_after,
        lease_epoch=lease.epoch,
    )
