# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-capability-scope-widening-attack-when-aaif-verifiable-credentials-are-re-presented-across-a-delegation-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-capability-scope-widening-attack-when-aaif-verifiable-credentials-are-re-presented-across-a-delegation-hop.warrant.json
# Markdown SHA-256:   18c172d8fc20d988f769f14824982ed9ad3c313ace59d183c0dd1504ee7c6c1c
# Code AST SHA-256:   8cc7bbf749614d993f94cb433f40547bbfc170d4a80451cb5f7b3ba705018f7b
# Verified Classes:   ScopeMonotonicityError, NormalizedScope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Tuple


class ScopeMonotonicityError(RuntimeError):
    """Raised when a re-presented AAIF credential's scope is not provably
    a subset of its parent's scope under the verifier's execution grammar."""


@dataclass(frozen=True)
class NormalizedScope:
    grammar_fingerprint: str
    grants: FrozenSet[Tuple[str, str]]  # (action, normalized_resource)


def normalize_scope(raw_scope: dict, grammar_fingerprint: str) -> NormalizedScope:
    # Canonicalize resources to exact, normalized paths; expand globs into
    # explicit sets ONLY if the grammar fingerprint matches the execution
    # matcher. Mismatched grammars are not coerced.
    grants = set()
    for action, resource in raw_scope.items():
        grants.add((action, _canonicalize(resource, grammar_fingerprint)))
    return NormalizedScope(grammar_fingerprint, frozenset(grants))


def _canonicalize(resource: str, grammar_fingerprint: str) -> str:
    if grammar_fingerprint != EXECUTION_GRAMMAR:
        raise ScopeMonotonicityError(
            f"grammar fingerprint {grammar_fingerprint!r} does not match "
            f"execution matcher {EXECUTION_GRAMMAR!r}; scope is undecidable"
        )
    # Normalize before matching so '..' cannot escape the subtree.
    return _posix_normalize(resource)


def verify_re_presentation(
    child_vc: dict, parent_vc: dict, execution_grammar: str
) -> NormalizedScope:
    child = normalize_scope(child_vc["scope"], child_vc["scope_grammar"])
    parent = normalize_scope(parent_vc["scope"], parent_vc["scope_grammar"])

    if child.grammar_fingerprint != execution_grammar:
        raise ScopeMonotonicityError(
            "child scope grammar does not match local execution matcher"
        )
    if not child.grants.issubset(parent.grants):
        widened = child.grants - parent.grants
        raise ScopeMonotonicityError(
            f"scope widening detected across delegation hop: {sorted(widened)}"
        )
    return child


EXECUTION_GRAMMAR = "aaif-scope-exact-v3"


def _posix_normalize(path: str) -> str:
    parts = []
    for seg in path.split("/"):
        if seg in ("", "."):
            continue
        if seg == "..":
            if parts:
                parts.pop()
            continue
        parts.append(seg)
    return "/" + "/".join(parts)
