# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-delegated-did-capability-chain-whose-intermediate-link-has-silently-expired-and-been-re-issued-under-a-rotated.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-delegated-did-capability-chain-whose-intermediate-link-has-silently-expired-and-been-re-issued-under-a-rotated.warrant.json
# Markdown SHA-256:   c2d559edf0b15d4218ae5d484e45a69f8b7128ecf147d735c7420a0ba4f2bc5a
# Code AST SHA-256:   9cd0a2496d7faf9c73c083b68618c81a370754eb8d46b219e5c29c6701ef47b6
# Verified Classes:   ChainDiscontinuity
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ChainDiscontinuity(RuntimeError):
    """Raised when a delegation link names a verification method that is not
    present in the resolved (current) DID document, and no historical
    resolution is available. Substituting the controller's current key is
    forbidden: it converts a key-scoped delegation into a DID-scoped one."""
    pass


def verify_link(link, resolved_doc, historical_resolver=None):
    named_vm = link.proof.get("verificationMethod")
    if named_vm is None:
        # Delegation scoped to the controller, not a specific key. Substitution
        # is permitted by the delegation itself.
        candidates = resolved_doc.verification_methods_for(link.subject)
    else:
        candidates = [vm for vm in resolved_doc.verification_methods_for(link.subject)
                      if vm.uri == named_vm]
        if not candidates:
            if historical_resolver is None:
                raise ChainDiscontinuity(
                    f"link {link.id} names {named_vm}, absent from current doc "
                    f"for {link.subject}; no historical resolver available. "
                    f"Refusing controller substitution."
                )
            historical_doc = historical_resolver.resolve_at(
                link.subject, link.proof["created"]
            )
            candidates = [vm for vm in historical_doc.verification_methods_for(link.subject)
                          if vm.uri == named_vm]
            if not candidates:
                raise ChainDiscontinuity(
                    f"link {link.id} names {named_vm}, absent even in historical "
                    f"doc at {link.proof['created']}."
                )

    for vm in candidates:
        if vm.verify(link.proof):
            return True

    raise ChainDiscontinuity(
        f"no named verification method validated link {link.id} for {link.subject}"
    )
