# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-delegated-scope-attenuation-failure-in-aaif-credential-chains-during-multi-hop-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-delegated-scope-attenuation-failure-in-aaif-credential-chains-during-multi-hop-agent-handoffs.warrant.json
# Markdown SHA-256:   fb98885f9afab3c627f30258ef60b9d32325de26bcaebc34f5cb2c97ed11142c
# Code AST SHA-256:   60de1cad54c255d734fea3655cfb8091510013b1fe295f7c9307493be5a7223e
# Verified Classes:   ScopeAttenuationError, ParentUnfetchableError, Scope
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ScopeAttenuationError(RuntimeError):
    """Raised when a delegated token's effective scope is not a strict subset of its parent's scope."""
    pass


class ParentUnfetchableError(RuntimeError):
    """Raised when the verifier cannot independently fetch the parent token to re-verify containment."""
    pass


@dataclass(frozen=True)
class Scope:
    action: str
    resource: str
    constraints: dict

    def canonical_hash(self) -> str:
        payload = json.dumps(
            {"action": self.action, "resource": self.resource, "constraints": self.constraints},
            sort_keys=True, separators=(",", ":"),
        )
        return hashlib.sha256(payload.encode()).hexdigest()


def narrow(parent: Scope, requested: Scope) -> Scope:
    """Deterministic attenuation. Rejects any field absent from parent; never defaults permissive."""
    if requested.action != parent.action or requested.resource != parent.resource:
        raise ScopeAttenuationError(
            f"action/resource mismatch: parent=({parent.action},{parent.resource}) "
            f"requested=({requested.action},{requested.resource})"
        )
    narrowed = {}
    for key, parent_val in parent.constraints.items():
        if key not in requested.constraints:
            raise ScopeAttenuationError(
                f"requested scope omits parent constraint '{key}'; omission is not permission"
            )
        req_val = requested.constraints[key]
        if isinstance(parent_val, list):
            if not set(req_val).issubset(set(parent_val)):
                raise ScopeAttenuationError(f"constraint '{key}' widens: {req_val} ⊄ {parent_val}")
            narrowed[key] = req_val
        elif isinstance(parent_val, int):
            if req_val > parent_val:
                raise ScopeAttenuationError(f"constraint '{key}' widens: {req_val} > {parent_val}")
            narrowed[key] = req_val
        else:
            if req_val != parent_val:
                raise ScopeAttenuationError(f"constraint '{key}' mutates: {req_val} != {parent_val}")
            narrowed[key] = req_val
    return Scope(parent.action, parent.resource, narrowed)


def verify_chain(child_scope: Scope, declared_parent_hash: str, fetch_parent) -> None:
    """RHA-side verification: fetch parent, recompute canonical hash, enforce containment."""
    try:
        parent_scope = fetch_parent()
    except Exception as exc:
        raise ParentUnfetchableError(f"cannot fetch parent for re-verification: {exc}") from exc

    actual_parent_hash = parent_scope.canonical_hash()
    if declared_parent_hash != actual_parent_hash:
        raise ScopeAttenuationError(
            f"scope-substitution: child declares parent hash {declared_parent_hash[:12]} "
            f"but fetched parent hashes to {actual_parent_hash[:12]}"
        )

    # Re-run narrowing against the live parent; any widening raises.
    narrow(parent_scope, child_scope)
