# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-attenuate-a-delegated-capability-token-when-the-aaif-chain-s-scope-lattice-is-only-partially-ordered.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-attenuate-a-delegated-capability-token-when-the-aaif-chain-s-scope-lattice-is-only-partially-ordered.warrant.json
# Markdown SHA-256:   f41a12179099b0fb9e62ae4fc2bf1f3989f283f4d53b65144efa6e940cca21b3
# Code AST SHA-256:   6235fcbd6decc15bd5571858f444b183748cbf8132f812ec2b480faba13b5270
# Verified Classes:   AttenuationRefused, Subsumption, Lattice, CapabilityToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, FrozenSet, Optional, Set, Tuple


class AttenuationRefused(RuntimeError):
    """Raised when a delegated capability token cannot be safely attenuated."""


class Subsumption(Enum):
    TRUE = "true"
    FALSE = "false"
    UNKNOWN = "unknown"          # relation undecidable in this lattice
    ATOM_ABSENT = "atom_absent"  # child atom not in parent lattice


@dataclass(frozen=True)
class Lattice:
    lattice_id: str                     # pinned as "L7:sha256:<digest>"
    atoms: FrozenSet[str]
    # partial order edges: (narrower, broader)
    edges: FrozenSet[Tuple[str, str]] = field(default_factory=frozenset)

    def subsumes(self, child_atom: str, parent_atom: str) -> Subsumption:
        if child_atom not in self.atoms or parent_atom not in self.atoms:
            return Subsumption.ATOM_ABSENT
        if child_atom == parent_atom:
            return Subsumption.TRUE
        # transitive closure over declared edges; absence of a path is UNKNOWN,
        # NOT FALSE — the lattice is partial, not total.
        seen: Set[str] = set()
        stack = [child_atom]
        while stack:
            node = stack.pop()
            if node in seen:
                continue
            seen.add(node)
            for lo, hi in self.edges:
                if lo == node:
                    if hi == parent_atom:
                        return Subsumption.TRUE
                    stack.append(hi)
        return Subsumption.UNKNOWN


@dataclass(frozen=True)
class CapabilityToken:
    subject: str
    scope: FrozenSet[str]
    lattice_id: str


def mint_child(parent: CapabilityToken, child_scope: FrozenSet[str],
               available: Dict[str, Lattice]) -> CapabilityToken:
    lattice = available.get(parent.lattice_id)
    if lattice is None:
        raise AttenuationRefused(
            f"parent lattice {parent.lattice_id!r} not available; "
            f"refusing to substitute a newer lattice at an attenuating hop"
        )
    for child_atom in child_scope:
        if child_atom not in lattice.atoms:
            raise AttenuationRefused(
                f"atom {child_atom!r} absent from pinned lattice "
                f"{parent.lattice_id!r}; atom introduction requires re-mint "
                f"from an authorized principal, not in-band attenuation"
            )
        for parent_atom in parent.scope:
            rel = lattice.subsumes(child_atom, parent_atom)
            if rel is Subsumption.TRUE:
                break
            if rel is Subsumption.UNKNOWN:
                raise AttenuationRefused(
                    f"relation {child_atom!r} ⊑ {parent_atom!r} undecidable in "
                    f"{parent.lattice_id!r}; fail closed on unknown"
                )
        else:
            raise AttenuationRefused(
                f"child atom {child_atom!r} not covered by any parent atom "
                f"{sorted(parent.scope)} in {parent.lattice_id!r}"
            )
    # invariant: child inherits the parent's pinned lattice_id, never upgrades.
    return CapabilityToken(
        subject=parent.subject,
        scope=child_scope,
        lattice_id=parent.lattice_id,
    )
