# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-delegated-aaif-credential-chain-when-scope-attenuation-is-not-strictly-monotonic-across-a-re-delegation-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-delegated-aaif-credential-chain-when-scope-attenuation-is-not-strictly-monotonic-across-a-re-delegation-hop.warrant.json
# Markdown SHA-256:   3ca8c1bcc56e28cf6246e741597b276dbefa1726aa2ab536a8146ea8cccc16bf
# Code AST SHA-256:   82e874994673c615c6fb07480d14609b10ba5112fd74d794e6a731e28874e6c7
# Verified Classes:   NonMonotonicDelegationError, ResolvedGrant, DelegatedCredential
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import FrozenSet, Mapping


class NonMonotonicDelegationError(RuntimeError):
    """Raised when a re-delegated AAIF credential does not strictly attenuate
    its parent's authority under a single pinned scope lattice."""


@dataclass(frozen=True)
class ResolvedGrant:
    scope_atoms: FrozenSet[str]
    expires_at: float
    max_rate: int
    purpose: FrozenSet[str]
    lattice_version: str


@dataclass(frozen=True)
class DelegatedCredential:
    subject: str
    delegator: str
    declared_scope: FrozenSet[str]
    expires_at: float
    max_rate: int
    purpose: FrozenSet[str]
    lattice_version: str
    delegation_path_hash: str
    max_delegation_depth: int
    current_depth: int


def resolve_scope(
    declared: FrozenSet[str], lattice_version: str
) -> FrozenSet[str]:
    # In production this dispatches to a pinned, versioned normalizer.
    # Unknown atoms must raise, not silently pass through.
    known = {"fs:read:", "fs:write:", "net:fetch:"}
    resolved = set()
    for atom in declared:
        if not any(atom.startswith(p) for p in known):
            raise NonMonotonicDelegationError(
                f"unresolvable scope atom {atom!r} under lattice {lattice_version}"
            )
        resolved.add(atom)
    return frozenset(resolved)


def admit_delegated_credential(
    child: DelegatedCredential,
    parent: ResolvedGrant,
    enforce_lattice_version: str,
) -> ResolvedGrant:
    if child.lattice_version != enforce_lattice_version:
        raise NonMonotonicDelegationError(
            f"lattice version skew: child minted under {child.lattice_version!r}, "
            f"enforced under {enforce_lattice_version!r}; containment undefined"
        )

    if child.current_depth > child.max_delegation_depth:
        raise NonMonotonicDelegationError(
            f"delegation depth {child.current_depth} exceeds cap "
            f"{child.max_delegation_depth}"
        )

    child_scope = resolve_scope(child.declared_scope, child.lattice_version)

    # Per-dimension monotonicity: scope, time, rate, purpose.
    if not child_scope.issubset(parent.scope_atoms):
        raise NonMonotonicDelegationError(
            f"scope expansion: {child_scope - parent.scope_atoms} not granted "
            f"by delegator {child.delegator!r}"
        )
    if child.expires_at > parent.expires_at:
        raise NonMonotonicDelegationError(
            f"temporal expansion: child lease {child.expires_at} exceeds "
            f"delegator lease {parent.expires_at}"
        )
    if child.max_rate > parent.max_rate:
        raise NonMonotonicDelegationError(
            f"rate expansion: {child.max_rate} > delegator {parent.max_rate}"
        )
    if not child.purpose.issubset(parent.purpose):
        raise NonMonotonicDelegationError(
            f"purpose expansion: {child.purpose - parent.purpose} outside "
            f"delegator purpose set"
        )

    return ResolvedGrant(
        scope_atoms=child_scope,
        expires_at=child.expires_at,
        max_rate=child.max_rate,
        purpose=child.purpose,
        lattice_version=child.lattice_version,
    )
