# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-aaif-credential-binding-as-invalid-when-its-own-delegated-warrant-outlives-the-issuing-parent-s-authorization.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-aaif-credential-binding-as-invalid-when-its-own-delegated-warrant-outlives-the-issuing-parent-s-authorization.warrant.json
# Markdown SHA-256:   1a2e78dd3de40a5eba2f5208d186dcfcf6747d6528a01e5a289ac902c85eada5
# Code AST SHA-256:   f85e592a7cb71540a59455b09429ccc7769b151bee650c4a7496889dcf2ea764
# Verified Classes:   WarrantChainInvalid, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class WarrantChainInvalid(RuntimeError):
    """Raised when an AAIF warrant fails transitive chain validation."""
    pass


@dataclass
class Warrant:
    subject: str
    scope: frozenset
    not_before: float
    not_after: float
    parent_hash: Optional[str] = None
    signature_ok: bool = True
    revoked: bool = False


def chain_valid(w: Warrant, ancestors: dict, now: Optional[float] = None) -> bool:
    """Recursive AAIF validity: signature + window + scope subset + monotonicity + revocation."""
    now = time.time() if now is None else now
    if not w.signature_ok:
        return False
    if w.revoked:
        return False
    if not (w.not_before <= now <= w.not_after):
        return False
    if w.parent_hash is None:
        return True  # root
    parent = ancestors.get(w.parent_hash)
    if parent is None:
        return False  # cannot ground the delegation
    if w.not_after > parent.not_after:
        return False  # monotonicity violated at issuance
    if not w.scope.issubset(parent.scope):
        return False  # scope drift
    return chain_valid(parent, ancestors, now)


def assert_authorized(w: Warrant, ancestors: dict, action_scope: frozenset,
                      now: Optional[float] = None) -> None:
    """Gate every externally-visible action on chain-valid, not locally-valid."""
    now = time.time() if now is None else now
    if not chain_valid(w, ancestors, now):
        # Find the specific broken link for diagnostics.
        cursor, depth = w, 0
        while cursor is not None:
            if cursor.revoked:
                raise WarrantChainInvalid(
                    f"ancestor at depth {depth} ({cursor.subject}) is revoked")
            if now > cursor.not_after:
                raise WarrantChainInvalid(
                    f"ancestor at depth {depth} ({cursor.subject}) expired at "
                    f"{cursor.not_after:.0f}; leaf window extends to {w.not_after:.0f}")
            cursor = ancestors.get(cursor.parent_hash) if cursor.parent_hash else None
            depth += 1
        raise WarrantChainInvalid("chain-valid check failed for unspecified reason")
    if not action_scope.issubset(w.scope):
        raise WarrantChainInvalid(
            f"action scope {sorted(action_scope)} not contained in warrant scope "
            f"{sorted(w.scope)}")


def issue_child(parent: Warrant, ancestors: dict, subject: str,
                scope: frozenset, requested_ttl: float,
                now: Optional[float] = None) -> Warrant:
    """Sub-delegation must refuse to outlive the chain, not silently clamp."""
    now = time.time() if now is None else now
    if not chain_valid(parent, ancestors, now):
        raise WarrantChainInvalid(
            f"refusing to delegate from invalid parent warrant for {parent.subject}")
    horizon = parent.not_after
    cursor = ancestors.get(parent.parent_hash) if parent.parent_hash else None
    while cursor is not None:
        horizon = min(horizon, cursor.not_after)
        cursor = ancestors.get(cursor.parent_hash) if cursor.parent_hash else None
    requested_expiry = now + requested_ttl
    if requested_expiry > horizon:
        raise WarrantChainInvalid(
            f"requested child expiry {requested_expiry:.0f} exceeds chain horizon "
            f"{horizon:.0f}; parent {parent.subject} cannot ground this delegation")
    return Warrant(
        subject=subject,
        scope=scope,
        not_before=now,
        not_after=requested_expiry,
        parent_hash=parent.subject,
    )
