# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-credential-chain-whose-depth-exceeds-its-own-trust-anchor-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-aaif-credential-chain-whose-depth-exceeds-its-own-trust-anchor-scope.warrant.json
# Markdown SHA-256:   e05ca9f26f4706f5809f7a074a213d7a1e8eaebdd321498776672ac2c14dbc4b
# Code AST SHA-256:   bf5b0b818c5ec8b46a2e639b6c7ab8fefae2cee3fb35179a91086bd0cab27d0b
# Verified Classes:   AnchorScopeViolation
# Defensive Guards:   8 fail-closed invariants (zero external deps)

class AnchorScopeViolation(RuntimeError):
    """Raised when a delegated AAIF chain is cryptographically valid but
    structurally deeper than the validating instance's trust anchor permits."""
    pass


def validate_delegated_chain(chain, anchor):
    """
    chain: list of hops, root-first. Each hop: {subject, cap, depth_used, sig_ok}
    anchor: {trusted_roots, max_depth, allowed_caps}
    Returns the effective leaf capability if admissible; raises otherwise.
    """
    if not chain:
        raise AnchorScopeViolation("empty chain")

    root = chain[0]
    if root["subject"] not in anchor["trusted_roots"]:
        raise AnchorScopeViolation(f"untrusted root: {root['subject']}")

    # Condition 1: signature closure (assumed pre-verified into sig_ok)
    for hop in chain:
        if not hop.get("sig_ok", False):
            raise AnchorScopeViolation(f"signature failure at {hop['subject']}")

    # Condition 3 FIRST: depth containment against the validator's own anchor.
    # Absence of depth metadata is treated as unbounded -> reject.
    leaf = chain[-1]
    leaf_depth = leaf.get("depth_used")
    if leaf_depth is None:
        raise AnchorScopeViolation(
            "leaf omits depth_used; cannot bound against anchor scope"
        )
    if leaf_depth > anchor["max_depth"]:
        raise AnchorScopeViolation(
            f"leaf depth {leaf_depth} exceeds anchor max_depth "
            f"{anchor['max_depth']}: credential inadmissible at this validator"
        )

    # Chain-internal depth monotonicity: each hop must consume exactly one
    # budget unit and never exceed its delegator's remaining budget.
    prev_depth = -1
    for hop in chain:
        d = hop.get("depth_used")
        if d is None or d != prev_depth + 1:
            raise AnchorScopeViolation(
                f"non-monotonic depth at {hop['subject']}: {d} after {prev_depth}"
            )
        prev_depth = d

    # Condition 2: capability monotonicity, then allowlist intersection.
    prev_caps = None
    for hop in chain:
        caps = set(hop["cap"])
        if prev_caps is not None and not caps.issubset(prev_caps):
            raise AnchorScopeViolation(
                f"capability widening at {hop['subject']}: {caps} not ⊆ {prev_caps}"
            )
        prev_caps = caps

    effective = set(leaf["cap"]) & set(anchor["allowed_caps"])
    if not effective:
        raise AnchorScopeViolation(
            f"leaf capability {leaf['cap']} disjoint from anchor allowlist"
        )
    return effective


def relay_handoff(chain, anchor, downstream_anchor):
    """
    On relay, the current validator must inject its own max_depth as a
    narrowing constraint so a deeper peer cannot honor what this validator
    was forbidden to originate.
    """
    effective = validate_delegated_chain(chain, anchor)
    narrowed = dict(downstream_anchor)
    narrowed["max_depth"] = min(downstream_anchor["max_depth"], anchor["max_depth"])
    # Downstream must re-validate under the narrowed anchor.
    return validate_delegated_chain(chain, narrowed), narrowed
