# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-agent-authorization-chain-has-silently-re-rooted-depth-collapse-in-aaif-verifiable-credential-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-agent-authorization-chain-has-silently-re-rooted-depth-collapse-in-aaif-verifiable-credential-chains.warrant.json
# Markdown SHA-256:   10fe2d796db2a8586c7bb5e53c357565d4ff443a8df76ad5356d753f69e6310c
# Code AST SHA-256:   0f70b7a44d2e495a125e2e90b380085bb22d621296f626915299091aef764a44
# Verified Classes:   ChainIntegrityError
# Defensive Guards:   9 fail-closed invariants (zero external deps)

class ChainIntegrityError(RuntimeError):
    """Raised when a presented AAIF delegation chain has a depth discontinuity
    or a parent link that does not resolve to the immediately preceding credential."""
    pass


def verify_delegation_chain(
    presented: list[dict],
    root_did: str,
    status_fetcher,
    max_status_age_s: int = 300,
) -> list[str]:
    """Verify an ordered AAIF delegation chain and return the effective scope set.

    Fails closed on any re-rooting: parent links must resolve by credential_id,
    depth must be monotonic, and every hop's status must be fresh.
    """
    if not presented:
        raise ChainIntegrityError("empty chain presented")

    # Order by delegation_depth; reject if depth is missing or non-contiguous.
    depths = [c.get("delegation_depth") for c in presented]
    if any(d is None for d in depths):
        raise ChainIntegrityError(
            f"missing delegation_depth on credential(s): "
            f"{[c['credential_id'] for c, d in zip(presented, depths) if d is None]}"
        )
    ordered = sorted(presented, key=lambda c: c["delegation_depth"])
    for i, cred in enumerate(ordered):
        if cred["delegation_depth"] != i:
            raise ChainIntegrityError(
                f"depth discontinuity: expected {i}, got {cred['delegation_depth']} "
                f"on {cred['credential_id']}"
            )

    # Root must be the ancestor of hop 0.
    if ordered[0]["parent_issuer"] != root_did:
        raise ChainIntegrityError(
            f"chain does not root at {root_did}: hop0 parent_issuer="
            f"{ordered[0]['parent_issuer']}"
        )

    effective_scope = set(ordered[0].get("scope", []))
    for i in range(1, len(ordered)):
        parent, child = ordered[i - 1], ordered[i]
        # The critical check: parent link must resolve by credential_id, not issuer DID.
        if child.get("parent_credential_id") != parent["credential_id"]:
            raise ChainIntegrityError(
                f"re-rooting detected: {child['credential_id']} claims parent "
                f"{child.get('parent_credential_id')} but predecessor is "
                f"{parent['credential_id']} (issuer {parent['issuer']})"
            )
        if child["parent_issuer"] != parent["issuer"]:
            raise ChainIntegrityError(
                f"issuer mismatch at hop {i}: child.parent_issuer="
                f"{child['parent_issuer']} parent.issuer={parent['issuer']}"
            )
        # Forced freshness: stale parent status is how re-rooting hides.
        status = status_fetcher(parent["credential_id"])
        if status["age_s"] > max_status_age_s:
            raise ChainIntegrityError(
                f"stale status for {parent['credential_id']}: "
                f"age {status['age_s']}s > {max_status_age_s}s"
            )
        if status["revoked"]:
            raise ChainIntegrityError(
                f"parent {parent['credential_id']} revoked; suffix invalid"
            )
        effective_scope &= set(child.get("scope", []))

    if len(presented) != len(ordered):
        raise ChainIntegrityError("presented/verified length mismatch")

    return sorted(effective_scope)
