# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-anchor-a-delegated-verifiable-credential-after-a-mid-chain-scope-narrowing-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-anchor-a-delegated-verifiable-credential-after-a-mid-chain-scope-narrowing-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   756dd24583ddbe538eacd3ec91a9aa6b1e9c9f291b56cc1bb81e042ae9bc885a
# Code AST SHA-256:   ed1bc29f1508f140e537857dc1fd9ef0c0f20e45b97836ec2dbc5ab95707bf01
# Verified Classes:   DelegationChainError, Credential, ChainStore
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DelegationChainError(RuntimeError):
    """Raised when an AAIF delegation chain cannot be re-anchored safely."""


@dataclass
class Credential:
    cred_id: str
    parent_hash: Optional[str]          # None for root
    scopes: frozenset[str]
    exp: float
    superseded_by: Optional[str] = None  # set when rotated; NOT revocation


@dataclass
class ChainStore:
    by_id: dict[str, Credential] = field(default_factory=dict)

    def resolve(self, cred_id: str) -> Credential:
        try:
            return self.by_id[cred_id]
        except KeyError:
            raise DelegationChainError(f"unresolvable credential {cred_id!r} in path")


def fold_live_chain(store: ChainStore, leaf_id: str, now: float) -> frozenset[str]:
    """Walk leaf -> root over LIVE nodes only; fold scopes by intersection."""
    path: list[Credential] = []
    cursor: Optional[str] = leaf_id
    seen: set[str] = set()
    while cursor is not None:
        if cursor in seen:
            raise DelegationChainError(f"cycle detected at {cursor!r}")
        seen.add(cursor)
        node = store.resolve(cursor)
        if node.superseded_by is not None:
            raise DelegationChainError(
                f"credential {node.cred_id!r} is superseded by "
                f"{node.superseded_by!r}; path is not live"
            )
        if node.exp <= now:
            raise DelegationChainError(
                f"credential {node.cred_id!r} expired at {node.exp}"
            )
        path.append(node)
        cursor = node.parent_hash
    if path[-1].parent_hash is not None:
        raise DelegationChainError("path does not terminate at a root")
    fold = path[0].scopes
    for node in path[1:]:
        fold = fold & node.scopes
    return fold


def reanchor(
    store: ChainStore,
    old_leaf_id: str,
    new_leaf: Credential,
    now: float,
) -> frozenset[str]:
    """Re-anchor a leaf and enforce monotone narrowing across the re-anchor."""
    old_fold = fold_live_chain(store, old_leaf_id, now)
    store.by_id[new_leaf.cred_id] = new_leaf
    try:
        new_fold = fold_live_chain(store, new_leaf.cred_id, now)
    except DelegationChainError:
        del store.by_id[new_leaf.cred_id]
        raise
    if not new_fold <= old_fold:
        del store.by_id[new_leaf.cred_id]
        raise DelegationChainError(
            f"re-anchor widened authority: {new_fold - old_fold} not in "
            f"original fold {old_fold}"
        )
    return new_fold
