# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-continue-an-aaif-delegated-credential-chain-after-a-scope-narrowing-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-continue-an-aaif-delegated-credential-chain-after-a-scope-narrowing-hop.warrant.json
# Markdown SHA-256:   5839bd93c6b9743bfad97b641b4569ce9d83c896b1445d6bb8c45d920789616d
# Code AST SHA-256:   b6e89b68898444d46b27fc816e98ea6e3f906ca582485537094fe3e3e3380cb4
# Verified Classes:   AAIFChainContinuityError, Credential
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import FrozenSet, Optional


class AAIFChainContinuityError(RuntimeError):
    """Raised when an instance cannot produce a bound transition record for a delegated hop."""


@dataclass(frozen=True)
class Credential:
    scope: FrozenSet[str]
    parent_hash: Optional[str]
    hop_index: int
    delta: FrozenSet[str]  # permissions removed at this hop; empty set is a valid zero-narrowing delta
    signature: str

    def content_hash(self) -> str:
        payload = f"{sorted(self.scope)}|{self.parent_hash}|{self.hop_index}|{sorted(self.delta)}"
        return hashlib.sha256(payload.encode()).hexdigest()


def continue_chain(
    incoming: Credential,
    child_scope: FrozenSet[str],
    signing_key: str,
    signing_available: bool = True,
) -> Credential:
    if not incoming.scope.issuperset(child_scope):
        raise AAIFChainContinuityError(
            f"requested child scope {sorted(child_scope)} exceeds incoming scope {sorted(incoming.scope)}"
        )
    if not signing_available:
        raise AAIFChainContinuityError("signing routine unavailable; cannot emit bound delta record")

    # The delta is the set difference between what we hold and what we grant.
    # For a zero-narrowing hop this is the empty set -- and it MUST be emitted explicitly.
    delta = incoming.scope - child_scope

    # Guard: if the signing routine lacks an empty-delta path, it will fall back to
    # replaying an ancestor's delta. Refuse instead of replaying.
    if not delta and incoming.delta and incoming.delta == incoming.delta:
        # Explicit empty-delta emission path; if the routine cannot represent it, refuse.
        pass  # empty delta is representable as frozenset(); proceed.

    parent_hash = incoming.content_hash()
    child = Credential(
        scope=child_scope,
        parent_hash=parent_hash,
        hop_index=incoming.hop_index + 1,
        delta=delta,
        signature=f"{signing_key}:{parent_hash}:{sorted(child_scope)}:{sorted(delta)}",
    )

    # Reconstruction check at the point of continuation: the chain must reconstruct
    # exactly. A replayed delta would fail this equality.
    if (incoming.scope - child.delta) != child.scope:
        raise AAIFChainContinuityError(
            "delta reconstruction mismatch: emitted delta does not reconstruct child scope"
        )
    return child


def verify_chain(root: Credential, chain: list[Credential]) -> None:
    current = root
    for hop in chain:
        if hop.parent_hash != current.content_hash():
            raise AAIFChainContinuityError(
                f"hop {hop.hop_index}: parent hash mismatch (possible splice or delta replay)"
            )
        if hop.hop_index != current.hop_index + 1:
            raise AAIFChainContinuityError(
                f"hop {hop.hop_index}: non-monotonic hop index"
            )
        if (current.scope - hop.delta) != hop.scope:
            raise AAIFChainContinuityError(
                f"hop {hop.hop_index}: delta replay detected; reconstruction failed"
            )
        current = hop
