# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-delegated-authority-when-a-verifiable-credential-s-scope-set-is-transitively-widened-by-an-intermedia.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-delegated-authority-when-a-verifiable-credential-s-scope-set-is-transitively-widened-by-an-intermedia.warrant.json
# Markdown SHA-256:   6244fc1872e234d30ad450b183bc85d7d481f1189f64e8fac93517b4720099d4
# Code AST SHA-256:   1b9b989e30c6ce59b282ed2d910d00369983e1a63d5cd9c101019308a3a3a7e5
# Verified Classes:   TransitiveScopeWideningError, Credential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional, Dict


class TransitiveScopeWideningError(RuntimeError):
    """Raised when a delegated credential asserts authority outside the
    running intersection of its ancestors' effective scopes."""
    pass


@dataclass(frozen=True)
class Credential:
    subject: str
    issuer: str
    scopes: FrozenSet[str]           # canonical resource:action tuples
    not_after: float
    issued_at: float
    parent_hash: Optional[str]       # hash of the exact parent credential
    cred_hash: str


def _canonical(scopes) -> FrozenSet[str]:
    # Normalize encodings to resource:action before any set operation.
    out = set()
    for s in scopes:
        if s.startswith("read:*"):
            out.add("read:all")
        elif "." in s and ":" not in s:
            res, act = s.split(".", 1)
            out.add(f"{act}:{res}")
        else:
            out.add(s)
    return frozenset(out)


def verify_chain(
    leaf: Credential,
    by_hash: Dict[str, Credential],
    now: float,
    vocab_version: int = 1,
) -> FrozenSet[str]:
    """Fold scope intersection from root to leaf. Returns effective authority."""
    chain = []
    cur: Optional[Credential] = leaf
    seen = set()
    while cur is not None:
        if cur.cred_hash in seen:
            raise TransitiveScopeWideningError(f"cycle at {cur.cred_hash}")
        seen.add(cur.cred_hash)
        chain.append(cur)
        if cur.parent_hash is None:
            break
        parent = by_hash.get(cur.parent_hash)
        if parent is None:
            raise TransitiveScopeWideningError(
                f"missing parent {cur.parent_hash} for {cur.cred_hash}; "
                "cannot fold, chain unverifiable"
            )
        cur = parent

    chain.reverse()  # root first
    root = chain[0]
    effective = _canonical(root.scopes)

    for cred in chain[1:]:
        declared = _canonical(cred.scopes)
        # The widening check: a hop may only narrow, never extend.
        widened = declared - effective
        if widened:
            raise TransitiveScopeWideningError(
                f"credential {cred.cred_hash} (issuer {cred.issuer}) asserts "
                f"{sorted(widened)} outside ancestor effective scope "
                f"{sorted(effective)}"
            )
        # Refresh-narrowing: a leaf that outlives an ancestor is suspect.
        if cred.not_after > max(c.not_after for c in chain[: chain.index(cred)]):
            raise TransitiveScopeWideningError(
                f"credential {cred.cred_hash} outlives its parent; "
                "re-fold required against current ancestor state"
            )
        effective = effective & declared

    return effective


def authorize(leaf: Credential, by_hash: Dict[str, Credential],
              requested: str, now: float) -> None:
    effective = verify_chain(leaf, by_hash, now)
    if _canonical({requested}) - effective:
        raise TransitiveScopeWideningError(
            f"requested {requested!r} not in effective authority {sorted(effective)}"
        )
