# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-complete-a-trust-anchor-handshake-when-the-peer-s-certificate-chain-validates-but-its-delegation-dept.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-complete-a-trust-anchor-handshake-when-the-peer-s-certificate-chain-validates-but-its-delegation-dept.warrant.json
# Markdown SHA-256:   06ff65902443e9580459f89ea3d5dce038f6258e8a67df662e1acada43116223
# Code AST SHA-256:   1b8a821eb9c1514f9470e7efd55d9c69c990a1eca41b073f66d4478b2d150a5b
# Verified Classes:   DelegationDepthExceeded
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class DelegationDepthExceeded(RuntimeError):
    """Raised when a cryptographically valid chain exceeds local federation policy depth.

    Distinct from UntrustedPeerError: the peer's anchor resolved and all
    signatures verified. Only this delegation path is inadmissible.
    """

    def __init__(self, observed_depth: int, policy_limit: int, offending_subject: str):
        self.observed_depth = observed_depth
        self.policy_limit = policy_limit
        self.offending_subject = offending_subject
        super().__init__(
            f"delegation depth {observed_depth} exceeds policy limit {policy_limit} "
            f"at intermediate '{offending_subject}'"
        )


def admit_federated_peer(chain, policy) -> bool:
    """Return True if the peer may be admitted under local federation policy.

    Precondition: chain has already passed cryptographic path validation
    against a configured trust anchor. This function decides *admissibility*,
    not *validity*.
    """
    if not chain.anchor_resolved:
        # Not a depth question; the peer is simply untrusted.
        raise UntrustedPeerError("anchor did not resolve to a configured trust anchor")

    intermediates = [c for c in chain.certificates if c.is_ca and not c.is_anchor]
    observed_depth = len(intermediates)

    if not policy.enforce_depth:
        # Explicit exemption for legacy realms; record, do not gate.
        chain.record_decision("exempt", observed_depth)
        return True

    if observed_depth > policy.max_delegation_depth:
        offending = intermediates[policy.max_delegation_depth].subject
        chain.record_decision("reject_chain", observed_depth)
        raise DelegationDepthExceeded(
            observed_depth=observed_depth,
            policy_limit=policy.max_delegation_depth,
            offending_subject=offending,
        )

    chain.record_decision("admit", observed_depth)
    return True
