# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-did-resolved-manifest-it-cannot-bind-to-the-current-transport-session.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-did-resolved-manifest-it-cannot-bind-to-the-current-transport-session.warrant.json
# Markdown SHA-256:   89475773ba917e75bd86e3423a7b30b6bcecfdc5714b9b577ade23b5db37c61e
# Code AST SHA-256:   37129f2de2df7c650e072e9121490be16480d3ec0cd137ce10803b8fc8f00830
# Verified Classes:   TrustBindingError, DidDocument, Manifest, Session
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class TrustBindingError(RuntimeError):
    """Raised when a DID-resolved manifest cannot be bound to the live transport session."""
    pass


@dataclass
class DidDocument:
    did: str
    controller: str
    verification_methods: dict  # key_id -> public_key
    updated: float              # unix ts of last key change


@dataclass
class Manifest:
    did: str
    signer_key_id: str
    controller: str
    iat: float
    chain: list  # list of (did, signer_key_id, signed_by_key_id)


@dataclass
class Session:
    presented_did: str
    transport_key_id: str
    nonce: str


def admit_peer(
    session: Session,
    manifest: Manifest,
    resolve: callable,
    verify_sig: callable,
    verify_pop: callable,
) -> bool:
    # 1. Anchor equality: the manifest's controller must be the DID presented in THIS session.
    if manifest.controller != session.presented_did:
        raise TrustBindingError(
            f"manifest controller {manifest.controller!r} does not match "
            f"session-presented DID {session.presented_did!r}"
        )

    # 2. Chain currency: every link must be signed by the current key of its predecessor,
    #    and the manifest must not predate the controller's latest key rotation.
    doc = resolve(manifest.controller)
    if manifest.iat < doc.updated:
        raise TrustBindingError(
            f"manifest iat {manifest.iat} predates controller key rotation at {doc.updated}; "
            f"rejecting stale manifest (no secondary-DID fallback permitted)"
        )

    for (did, signer_key_id, signed_by_key_id) in manifest.chain:
        link_doc = resolve(did)
        if signer_key_id not in link_doc.verification_methods:
            raise TrustBindingError(
                f"chain link {did} signer key {signer_key_id} not present in current DID document"
            )
        if not verify_sig(did, signer_key_id, signed_by_key_id):
            raise TrustBindingError(
                f"chain link {did} signature by {signed_by_key_id} failed verification"
            )

    # 3. Transport binding: the session key must appear as a delegated key in the chain,
    #    or the peer must prove possession of the manifest signer over the session nonce.
    chain_key_ids = {k for (_, k, _) in manifest.chain}
    if session.transport_key_id not in chain_key_ids:
        if not verify_pop(manifest.signer_key_id, session.nonce):
            raise TrustBindingError(
                f"transport key {session.transport_key_id} not bound to manifest signer "
                f"{manifest.signer_key_id} and no proof-of-possession over session nonce"
            )

    return True


def handshake(session, manifest, resolve, verify_sig, verify_pop) -> bool:
    try:
        return admit_peer(session, manifest, resolve, verify_sig, verify_pop)
    except TrustBindingError:
        # Do NOT retry with a secondary DID. A binding failure is terminal for this session.
        raise
