# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-present-a-delegated-aaif-credential-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-present-a-delegated-aaif-credential-chain.warrant.json
# Markdown SHA-256:   1e4444dd24bf4ddb68dd04a0ebf56ec5bdb725a7fd59349a3a2df5224a30b969
# Code AST SHA-256:   7ed0f72fbedf371a4e98989c011ba7dcdde5a39157ded39ae399b4db50b83d44
# Verified Classes:   ChainNotPresentableError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ChainNotPresentableError(RuntimeError):
    """Raised when an AAIF instance holds a valid chain it must not present.

    The chain verifies against the root and every hop signature is intact,
    but the terminal hop does not bind the key this instance is currently
    using. Presenting it would either be rejected downstream or, worse,
    admitted under a key the chain does not name.
    """


def assert_chain_presentable(
    chain: dict,
    own_agent_id: str,
    own_public_key_fingerprint: str,
) -> None:
    terminal = chain["hops"][-1]
    subject = terminal["credentialSubject"]

    if subject["id"] != own_agent_id:
        raise ChainNotPresentableError(
            f"terminal subject {subject['id']!r} is not this instance "
            f"({own_agent_id!r}); chain is valid but belongs to another agent"
        )

    if subject["publicKeyFingerprint"] != own_public_key_fingerprint:
        raise ChainNotPresentableError(
            "terminal hop binds key "
            f"{subject['publicKeyFingerprint']!r} but this instance holds "
            f"{own_public_key_fingerprint!r}; key rotated without re-issuing "
            "terminal hop -- request re-issuance from delegator"
        )

    if terminal.get("delegationDepth", 0) < 0:
        raise ChainNotPresentableError("negative delegation depth is malformed")


def present(chain, own_agent_id, own_key_fp, nonce_signer):
    assert_chain_presentable(chain, own_agent_id, own_key_fp)
    return {
        "chain": chain,
        "nonceSignature": nonce_signer.sign(chain["challengeNonce"]),
    }
