# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-capability-token-whose-scope-was-narrowed-by-a-non-ancestor-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-capability-token-whose-scope-was-narrowed-by-a-non-ancestor-hop.warrant.json
# Markdown SHA-256:   a0411bbaf0eca586a576a8e1847c437728f3e744f522ca91c33945b19bd62582
# Code AST SHA-256:   34e9fef2eccc389ee6b6c14e815f39f6abc1c61c75afb8410149c4c84546bf16
# Verified Classes:   DelegationAncestryError, ScopedToken
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass
from typing import Optional


class DelegationAncestryError(RuntimeError):
    """Raised when a delegated AAIF token's ancestry or narrowing invariant fails."""
    pass


@dataclass(frozen=True)
class ScopedToken:
    token_id: str
    parent_id: Optional[str]
    subject: str
    scope_segments: tuple  # normalized, e.g. ("files:read", "tenant", "a", "audit")
    issuer: str


def _is_segment_subset(child: tuple, parent: tuple) -> bool:
    # Segment-wise containment; string-prefix match is explicitly NOT used.
    if len(child) < len(parent):
        return False
    return child[: len(parent)] == parent


def verify_delegated_chain(
    presented: ScopedToken,
    token_store: dict,
    trusted_roots: set,
    presenter: str,
    max_depth: int = 8,
) -> ScopedToken:
    chain = []
    cursor: Optional[ScopedToken] = presented
    seen = set()

    while cursor is not None:
        if cursor.token_id in seen:
            raise DelegationAncestryError(f"cycle at {cursor.token_id}")
        seen.add(cursor.token_id)
        chain.append(cursor)
        if len(chain) > max_depth:
            raise DelegationAncestryError("delegation depth exceeded")
        if cursor.parent_id is None:
            break
        parent = token_store.get(cursor.parent_id)
        if parent is None:
            raise DelegationAncestryError(
                f"unresolvable parent {cursor.parent_id} for {cursor.token_id}"
            )
        cursor = parent

    root = chain[-1]
    if root.issuer not in trusted_roots:
        raise DelegationAncestryError(f"chain root {root.issuer} not trusted")

    # Monotonic narrowing along the *resolved* path, segment-wise.
    for child, parent in zip(chain, chain[1:]):
        if not _is_segment_subset(child.scope_segments, parent.scope_segments):
            raise DelegationAncestryError(
                f"scope of {child.token_id} {child.scope_segments} "
                f"not contained in ancestor {parent.token_id} {parent.scope_segments}"
            )

    # Presenter binding: the leaf must be the presenter or re-delegated from it.
    if presented.subject != presenter:
        raise DelegationAncestryError(
            f"presenter {presenter} does not match subject {presented.subject}"
        )

    return presented


def authorize_operation(
    presented: ScopedToken,
    token_store: dict,
    trusted_roots: set,
    presenter: str,
    target_segments: tuple,
) -> None:
    token = verify_delegated_chain(presented, token_store, trusted_roots, presenter)
    if not _is_segment_subset(target_segments, token.scope_segments):
        raise DelegationAncestryError(
            f"target {target_segments} outside authorized scope {token.scope_segments}"
        )
