# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-aaif-delegated-scope-attenuation-has-silently-inverted-during-multi-hop-credential-chaining.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-aaif-delegated-scope-attenuation-has-silently-inverted-during-multi-hop-credential-chaining.warrant.json
# Markdown SHA-256:   fa2bd19fbb6d1ff06341c04c61fe59f88ade366cef12be4463f5e51b21961ea9
# Code AST SHA-256:   4c056466bd4bf15e2049371f7ad403d85fe0017824b6f3410b18e71b06c6b9a5
# Verified Classes:   DelegationScopeInversionError, Credential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class DelegationScopeInversionError(RuntimeError):
    """Raised when a delegated VC's effective scope is not a subset of its
    immediate issuer's effective scope, or its delegation_basis skips a hop."""


@dataclass
class Credential:
    cred_id: str
    issuer_id: str
    subject_id: str
    declared_scope: frozenset
    delegation_basis: str | None  # cred_id of the immediate issuer's VC
    attenuation: frozenset | None  # elements removed relative to basis


def _digest(cred: Credential) -> str:
    h = hashlib.sha256()
    h.update(cred.cred_id.encode())
    h.update(cred.issuer_id.encode())
    h.update(cred.subject_id.encode())
    h.update(repr(sorted(cred.declared_scope)).encode())
    return h.hexdigest()


def recompute_chain(root: Credential, chain: list[Credential]) -> dict[str, frozenset]:
    """Recompute effective scope per node, enforcing consecutive-hop monotonicity
    and basis-pointer identity. Fails closed on any skip-edge or widening."""
    effective: dict[str, frozenset] = {root.cred_id: root.declared_scope}
    by_id = {c.cred_id: c for c in chain}

    for cred in chain:
        basis_id = cred.delegation_basis
        if basis_id is None:
            raise DelegationScopeInversionError(
                f"{cred.cred_id}: missing delegation_basis"
            )
        if basis_id not in effective:
            raise DelegationScopeInversionError(
                f"{cred.cred_id}: basis {basis_id} not an ancestor in effective set "
                f"(skip-edge or out-of-order chain)"
            )
        parent_scope = effective[basis_id]
        # Consecutive-hop subset check against the *immediate* issuer, not root.
        if not cred.declared_scope <= parent_scope:
            widened = cred.declared_scope - parent_scope
            raise DelegationScopeInversionError(
                f"{cred.cred_id}: effective scope widens past immediate issuer "
                f"{basis_id}; unauthorized elements={sorted(widened)}"
            )
        # Basis-pointer identity: must reference the immediate issuer's credential,
        # not a grandparent. Here we assert the basis credential's subject is this cred's issuer.
        basis_cred = by_id.get(basis_id) or (root if basis_id == root.cred_id else None)
        if basis_cred is None or basis_cred.subject_id != cred.issuer_id:
            raise DelegationScopeInversionError(
                f"{cred.cred_id}: delegation_basis {basis_id} does not belong to "
                f"immediate issuer {cred.issuer_id} (authority-graph inversion)"
            )
        effective[cred.cred_id] = cred.declared_scope

    return effective


def authorize_write(chain_effective: dict[str, frozenset], node_id: str, resource: str) -> None:
    scope = chain_effective.get(node_id, frozenset())
    if f"write:{resource}" not in scope:
        raise DelegationScopeInversionError(
            f"node {node_id} lacks write:{resource}; scope={sorted(scope)}"
        )
