# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-aaif-capability-token-that-validates-cryptographically-but-exceeds-the-delegator-s-residual-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-aaif-capability-token-that-validates-cryptographically-but-exceeds-the-delegator-s-residual-scope.warrant.json
# Markdown SHA-256:   8b664979924199b0478a34fcb89cb36c726797f3abcb0d44e5256c1553cedaff
# Code AST SHA-256:   f72ea8bff52a0741d9dad26bcfb5aada3e2a96d1ac008764cf03068741b0ead9
# Verified Classes:   DelegationScopeError, Scope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class DelegationScopeError(RuntimeError):
    """Raised when a delegated AAIF token is authentic but not authorized."""


@dataclass(frozen=True)
class Scope:
    # Simplified AAIF scope algebra: resource paths + tenant constraint set.
    paths: FrozenSet[str]          # e.g. {"dataset/A", "dataset/*"}
    allowed_tenants: FrozenSet[str]  # empty == unconstrained (weakest)


def _path_contains(parent: str, child: str) -> bool:
    if parent == child:
        return True
    if parent.endswith("/*"):
        return child.startswith(parent[:-1])
    return False


def scope_subset(child: Scope, parent: Scope) -> bool:
    # Every child path must be contained by some parent path.
    for cp in child.paths:
        if not any(_path_contains(pp, cp) for pp in parent.paths):
            return False
    # Constraint implication: child must be at least as strict as parent.
    # Unconstrained parent (empty set) imposes nothing; constrained parent
    # requires child to be a subset of the parent's allowed tenants.
    if parent.allowed_tenants:
        if not child.allowed_tenants:
            return False  # child dropped a constraint -> escalation
        if not child.allowed_tenants.issubset(parent.allowed_tenants):
            return False
    return True


def residual_scope(ancestor_scopes: list[Scope], consumed_paths: FrozenSet[str]) -> Scope:
    # Intersection of all ancestors, minus consumed paths.
    paths = set(ancestor_scopes[0].paths)
    tenants = set(ancestor_scopes[0].allowed_tenants)
    for s in ancestor_scopes[1:]:
        paths = {p for p in paths if any(_path_contains(q, p) for q in s.paths)}
        tenants = (tenants & s.allowed_tenants) if s.allowed_tenants else tenants
    paths -= consumed_paths
    return Scope(frozenset(paths), frozenset(tenants))


def authorize_delegated_token(
    presented_scope: Scope,
    presented_expiry: int,
    parent_expiry: int,
    ancestor_scopes: list[Scope],
    consumed_paths: FrozenSet[str],
    parent_scope_digest_ok: bool,
    now: int,
) -> None:
    if presented_expiry > parent_expiry:
        raise DelegationScopeError(
            "child token outlives parent authority (temporal escalation)"
        )
    if presented_expiry <= now:
        raise DelegationScopeError("token expired at verification time")
    if not parent_scope_digest_ok:
        raise DelegationScopeError(
            "parent_scope_digest does not bind to parent's actual granted scope; "
            "mint provenance untrustworthy for this token"
        )
    residual = residual_scope(ancestor_scopes, consumed_paths)
    if not scope_subset(presented_scope, residual):
        raise DelegationScopeError(
            f"attenuation violated: presented {presented_scope} not a subset "
            f"of delegator residual {residual}"
        )
