# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-delegated-credential-exchange-under-aaif-when-its-own-scope-attenuates-a-parent-warrant-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-delegated-credential-exchange-under-aaif-when-its-own-scope-attenuates-a-parent-warrant-mid-chain.warrant.json
# Markdown SHA-256:   28d6b95b944d79f33237561414bff45c5a37f53633ad99d2bb1ed16483a2b429
# Code AST SHA-256:   e62f8adb598382923bd2c53737a51d14df3ee493966f04dc7f6b5b6f76bd3b70
# Verified Classes:   DelegationReexpansionError, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DelegationReexpansionError(RuntimeError):
    """Raised when a child warrant asserts a constraint dimension its parent does not carry."""
    pass


@dataclass
class Warrant:
    issuer: str
    subject: str
    actions: frozenset
    tenant: Optional[str] = None
    max_depth: Optional[int] = None
    not_after: Optional[float] = None
    parent_scope_hash: Optional[str] = None
    is_root: bool = False

    def dimensions(self) -> dict:
        return {
            "tenant": self.tenant,
            "max_depth": self.max_depth,
            "not_after": self.not_after,
            "actions": self.actions,
        }


def mint_child(parent: Warrant, requested: Warrant, ancestry_dims: set) -> Warrant:
    if parent.is_root:
        # Root may mint freely within its own scope.
        return requested

    parent_dims = {k for k, v in parent.dimensions().items() if v is not None}
    missing = ancestry_dims - parent_dims

    for dim in missing:
        requested_val = requested.dimensions().get(dim)
        # Sentinel None counts as absent, not as unconstrained.
        if requested_val is not None:
            raise DelegationReexpansionError(
                f"cannot mint child: parent lacks ancestry dimension '{dim}' "
                f"(parent_scope_hash={parent.parent_scope_hash}); "
                f"child asserts {dim}={requested_val!r}. Refuse and escalate to issuer."
            )

    # Intersect time dimension rather than recompute from local clock.
    if parent.not_after is not None and requested.not_after is not None:
        requested.not_after = min(parent.not_after, requested.not_after)

    # Intersect depth rather than recompute from declared depth.
    if parent.max_depth is not None:
        requested.max_depth = min(parent.max_depth - 1, requested.max_depth or parent.max_depth - 1)
        if requested.max_depth < 0:
            raise DelegationReexpansionError("delegation depth exhausted at this hop")

    return requested
