# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-aaif-delegated-credential-chain-collapse-at-the-scope-narrowing-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-aaif-delegated-credential-chain-collapse-at-the-scope-narrowing-boundary.warrant.json
# Markdown SHA-256:   f7a0539d70a062a1eb85376fc0ffeadeb0fd6caf5575678fca7c5babe0b58785
# Code AST SHA-256:   1dc634fd624d4560748d4401725bd3ba7550b355c8a6cb41b83ea74d4395672f
# Verified Classes:   DelegationChainViolation, Credential
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class DelegationChainViolation(RuntimeError):
    """Raised when an AAIF delegated credential violates scope monotonicity or parent binding."""
    pass


@dataclass(frozen=True)
class Credential:
    credential_id: str
    issuer_id: str
    delegate_to: str
    scope: frozenset[str]
    signed_scope_bytes: bytes      # exact bytes covered by issuer signature
    parent_id: str | None
    parent_hash: str | None        # sha256 over parent's signed_scope_bytes


def _hash_scope(signed_scope_bytes: bytes) -> str:
    return hashlib.sha256(signed_scope_bytes).hexdigest()


def verify_chain(chain: list[Credential]) -> None:
    """
    Verify an AAIF delegation chain root->...->leaf under the strict boundary:
    each hop's parent_hash must equal sha256(parent.signed_scope_bytes) AND
    child.scope must be a strict subset of parent.scope decoded from signed bytes.
    A hash mismatch is a hard rejection even if the subset check passes.
    """
    if not chain:
        raise DelegationChainViolation("empty chain")

    root = chain[0]
    if root.parent_id is not None or root.parent_hash is not None:
        raise DelegationChainViolation(
            f"root credential {root.credential_id} must not declare a parent"
        )

    by_id = {c.credential_id: c for c in chain}
    for child in chain[1:]:
        if child.parent_id is None:
            raise DelegationChainViolation(
                f"non-root credential {child.credential_id} missing parent_id"
            )
        parent = by_id.get(child.parent_id)
        if parent is None:
            raise DelegationChainViolation(
                f"credential {child.credential_id} references unknown parent {child.parent_id}"
            )
        if parent.delegate_to != child.issuer_id:
            raise DelegationChainViolation(
                f"issuer mismatch: {child.issuer_id} is not the delegate of {parent.credential_id}"
            )

        expected_hash = _hash_scope(parent.signed_scope_bytes)
        if child.parent_hash != expected_hash:
            # Structural signal: issuer minted against a drifted representation of its own scope.
            raise DelegationChainViolation(
                f"parent binding broken for {child.credential_id}: "
                f"parent_hash={child.parent_hash} expected={expected_hash}"
            )

        parent_scope = frozenset(json.loads(parent.signed_scope_bytes.decode("utf-8")))
        if not child.scope.issubset(parent_scope):
            widening = child.scope - parent_scope
            raise DelegationChainViolation(
                f"scope widening at {child.credential_id}: {sorted(widening)} not held by parent"
            )


def issue_child(parent: Credential, requested_scope: frozenset[str], child_id: str,
                delegate_to: str, issuer_id: str) -> Credential:
    """
    Mint a narrowed child credential. Fails closed if the requested scope is not a
    subset of the parent's signed scope, and binds parent_hash to signed bytes.
    """
    parent_scope = frozenset(json.loads(parent.signed_scope_bytes.decode("utf-8")))
    if not requested_scope.issubset(parent_scope):
        raise DelegationChainViolation(
            f"refusing to issue {child_id}: requested {sorted(requested_scope - parent_scope)} "
            f"exceeds signed parent scope of {parent.credential_id}"
        )
    child_scope_bytes = json.dumps(sorted(requested_scope)).encode("utf-8")
    return Credential(
        credential_id=child_id,
        issuer_id=issuer_id,
        delegate_to=delegate_to,
        scope=requested_scope,
        signed_scope_bytes=child_scope_bytes,
        parent_id=parent.credential_id,
        parent_hash=_hash_scope(parent.signed_scope_bytes),
    )
