"""Brain-to-brain federation (V2 transport): sealed envelopes over a dumb relay.

The engine side of docs/V4-FEDERATION.md. Two laws, absolute here and in every
consumer of this package:

1. **Push-only, always.** A peer can never read, query, or pull from a brain.
   The only inbound federation artifact a brain ever processes is a sealed
   envelope it *fetched itself* from its own relay mailbox.
2. **Owner-fired.** Content leaves a brain only on the owner's command — the
   agent stages, the owner fires. Protocol receipts are the one automatic
   egress, and they carry delivery status, never vault content.

The **envelope is the trust boundary** — never the transport, never the relay.
The relay stores ciphertext it cannot open and authenticates nothing about
identity; a successful ``Box`` open against a paired peer's public key IS the
authentication.

Layout (docs/V4-FEDERATION.md §1):

- ``words.py``    — the frozen wordlists (pairing codes, verification words)
- ``identity.py`` — X25519 keypair, ``ax1…`` fingerprint, verification words
- ``envelope.py`` — seal/open, schema + size cap, receipt bodies

Crypto comes from PyNaCl (libsodium), shipped behind the ``federation`` extra
and imported lazily through :func:`sodium` — a brain without the extra keeps
working and gets an error naming the exact install, never an ImportError
traceback from three frames down (the extract.py doctrine).

Secrets discipline: private keys, mailbox bearers, and deposit tokens live
under ``$ALEXANDRIA_STATE_DIR/federation/`` (mode 0600) and nowhere else —
never in the vault repo, never in ``Agent/config.json``, never in a log line.
"""


class FederationUnavailable(RuntimeError):
    """Federation was asked for but PyNaCl (the ``federation`` extra) is missing."""


def sodium():
    """Import PyNaCl lazily, at use time — never at module import.

    Returns the top-level ``nacl`` package with ``public``, ``secret``,
    ``utils``, and ``exceptions`` loaded.
    """
    try:
        import nacl.exceptions  # noqa: F401
        import nacl.public  # noqa: F401
        import nacl.secret  # noqa: F401
        import nacl.utils  # noqa: F401

        import nacl
        return nacl
    except ImportError as exc:
        raise FederationUnavailable(
            "brain-to-brain federation needs PyNaCl, a CORE dependency of this brain — "
            "if it's missing, the app venv was built incompletely. Rebuild it: re-run "
            "`alexandria update`, or in the brain's venv `pip install -e <path-to-app>`."
        ) from exc
