# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-stop-trusting-a-delegated-aaif-credential-chain-the-depth-collapse-boundary-at-the-verification-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-stop-trusting-a-delegated-aaif-credential-chain-the-depth-collapse-boundary-at-the-verification-hop.warrant.json
# Markdown SHA-256:   7f35ec1ed52d40a4d761fdaba83ed1f6652f5dab556840949c7550b3abaad473
# Code AST SHA-256:   52649921e0a67dcd989002f6eba96fff03567437465593d7bd87012aa5665ece
# Verified Classes:   DelegationDepthCollapseError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class DelegationDepthCollapseError(RuntimeError):
    """Raised when a verifier accepts a credential whose chain was not fully replayed."""
    pass


def verify_delegation_chain(chain, max_chain_depth, recompute_scope=True):
    """
    chain: list of credentials ordered root -> leaf.
    Each hop: {"did": str, "parent_hash": str, "scope": set, "signature_valid": bool}
    Returns a verdict dict. Raises on depth collapse if strict mode is violated.
    """
    hops_present = len(chain)
    hops_verified = 0
    scope_intersection = None

    for i, hop in enumerate(chain):
        if i >= max_chain_depth:
            # Depth budget exhausted mid-chain. The safe outcome is indeterminate,
            # never valid. If a caller tries to treat this as valid, raise.
            verdict = {
                "valid": False,
                "indeterminate": True,
                "hops_present": hops_present,
                "hops_verified": hops_verified,
                "scope_recomputed": False,
                "reason": "depth_budget_exhausted",
            }
            if hops_verified < hops_present and verdict.get("valid"):
                raise DelegationDepthCollapseError(
                    f"verifier accepted leaf scope with only {hops_verified}/{hops_present} hops verified"
                )
            return verdict

        if not hop["signature_valid"]:
            return {"valid": False, "reason": f"bad_signature_at_hop_{i}"}

        if i > 0:
            parent_hash = chain[i - 1].get("hash")
            if hop["parent_hash"] != parent_hash:
                return {"valid": False, "reason": f"parent_hash_mismatch_at_hop_{i}"}

        if recompute_scope:
            if scope_intersection is None:
                scope_intersection = set(hop["scope"])
            else:
                if not set(hop["scope"]).issubset(scope_intersection):
                    return {
                        "valid": False,
                        "reason": f"scope_widening_at_hop_{i}",
                        "declared": sorted(hop["scope"]),
                        "allowed": sorted(scope_intersection),
                    }
                scope_intersection &= set(hop["scope"])

        hops_verified += 1

    if hops_verified != hops_present:
        raise DelegationDepthCollapseError(
            f"hops_verified={hops_verified} != hops_present={hops_present}; refusing to emit valid"
        )

    return {
        "valid": True,
        "indeterminate": False,
        "hops_present": hops_present,
        "hops_verified": hops_verified,
        "scope_recomputed": recompute_scope,
        "scope": sorted(scope_intersection) if scope_intersection is not None else None,
    }
