# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-delegation-scope-collapse-in-aaif-capability-tokens-under-transitive-re-issuance.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-delegation-scope-collapse-in-aaif-capability-tokens-under-transitive-re-issuance.warrant.json
# Markdown SHA-256:   7e38caec4a460df7a3c8049bd50110ca36ccc96d5c9f83aeab5a3e6d7d747544
# Code AST SHA-256:   5d869322bd5c3f8612b3b42c00fad24a919bd8d3ecae962c5a2a81e988dbb810
# Verified Classes:   DelegationScopeError, Predicate, CapabilityToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import FrozenSet, Tuple, Optional


class DelegationScopeError(RuntimeError):
    """Raised when a re-issued capability token violates AAIF delegation invariants."""
    pass


@dataclass(frozen=True)
class Predicate:
    key: str
    op: str  # one of: "eq", "le", "ge", "in"
    value: object


@dataclass(frozen=True)
class CapabilityToken:
    allow_set: FrozenSet[str]          # fully qualified: "verb:resource_type:selector"
    predicates: Tuple[Predicate, ...]
    audience: str
    delegation_depth: int
    parent_chain_hash: Optional[str]   # None for root
    token_bytes: bytes = field(default=b"")

    def chain_hash(self) -> str:
        return hashlib.sha256(self.token_bytes).hexdigest()


def _namespace_subset(child: FrozenSet[str], parent: FrozenSet[str]) -> bool:
    # Fully qualified containment; a bare verb match is NOT sufficient.
    return child.issubset(parent)


def _predicates_satisfiable(preds: Tuple[Predicate, ...], request: dict) -> bool:
    for p in preds:
        if p.key not in request:
            return False
        actual = request[p.key]
        if p.op == "eq" and actual != p.value:
            return False
        if p.op == "le" and not (actual <= p.value):
            return False
        if p.op == "ge" and not (actual >= p.value):
            return False
        if p.op == "in" and actual not in p.value:
            return False
    return True


def issue_delegated_token(
    parent: CapabilityToken,
    child_allow: FrozenSet[str],
    child_preds: Tuple[Predicate, ...],
    child_audience: str,
    depth_ceiling: int = 3,
) -> CapabilityToken:
    if not _namespace_subset(child_allow, parent.allow_set):
        raise DelegationScopeError(
            f"SCOPE_NOT_SUBSET: child allow-set {sorted(child_allow)} not contained "
            f"in parent {sorted(parent.allow_set)} under fully qualified namespace"
        )

    new_depth = parent.delegation_depth + 1
    if new_depth > depth_ceiling:
        raise DelegationScopeError(
            f"DEPTH_EXCEEDED: chain depth {new_depth} exceeds ceiling {depth_ceiling}; "
            f"refusing re-issuance"
        )

    # Chain continuity: child must commit to parent's hash.
    parent_hash = parent.chain_hash()
    if parent.parent_chain_hash is not None and parent_hash == "":
        raise DelegationScopeError("CHAIN_INTEGRITY_FAILURE: parent hash uncomputable")

    # Conjoin predicates: child inherits ALL ancestor predicates.
    conjoined = tuple(parent.predicates) + tuple(child_preds)

    token_bytes = repr(
        (child_allow, conjoined, child_audience, new_depth, parent_hash)
    ).encode()

    return CapabilityToken(
        allow_set=child_allow,
        predicates=conjoined,
        audience=child_audience,
        delegation_depth=new_depth,
        parent_chain_hash=parent_hash,
        token_bytes=token_bytes,
    )


def authorize_side_effect(token: CapabilityToken, request: dict, action: str) -> None:
    """Must be called BEFORE any side effect. Evaluates conjoined predicates."""
    if action not in token.allow_set:
        raise DelegationScopeError(
            f"ACTION_NOT_PERMITTED: {action} not in token allow-set"
        )
    if not _predicates_satisfiable(token.predicates, request):
        raise DelegationScopeError(
            f"UNSATISFIABLE_PREDICATE: conjoined predicates {token.predicates} "
            f"not satisfied by request {request}; side effect blocked"
        )
    if token.delegation_depth > 3:
        raise DelegationScopeError(
            f"CHAIN_INTEGRITY_FAILURE: depth {token.delegation_depth} exceeds ceiling"
        )
    # Only now may the caller perform the side effect.
