#!/usr/bin/env -S uv run --no-project --python >=3.12 python
"""Load an explicitly selected MCP credential into the child environment only.

tmux can predate credential environment changes. The pane-local bootstrap
reads the file immediately before replacing itself, without putting token
values in arguments, configuration, tmux server environment, state files or
launcher output. MCP clients run in the shared Codex daemon, which does not
inherit this environment: set its token with `launchctl setenv
PRECIS_MCP_TOKEN` and restart the daemon (runbook codex-fleet). `--no-daemon`
is refused because embedded mode breaks code mode, the only route to MCP tools.
"""

from __future__ import annotations

import argparse
import os
import sys
from pathlib import Path


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--token-file", type=Path)
    parser.add_argument("command", nargs=argparse.REMAINDER)
    args = parser.parse_args()
    command = args.command[1:] if args.command[:1] == ["--"] else args.command
    if "--no-daemon" in command:
        parser.error("--no-daemon breaks Codex code mode; launch on the daemon")
    environment = os.environ.copy()
    if args.token_file:
        try:
            token = args.token_file.read_text(encoding="utf-8").strip()
        except (OSError, UnicodeError):
            print("codex-fleet-session: cannot read token file", file=sys.stderr)
            return 2
        if not token or any(
            character.isspace() or character == "\0" for character in token
        ):
            print("codex-fleet-session: invalid token file", file=sys.stderr)
            return 2
        environment["PRECIS_MCP_TOKEN"] = token
    try:
        os.execvpe("codex", ["codex", *command], environment)
    except OSError:
        print("codex-fleet-session: cannot execute codex", file=sys.stderr)
        return 2
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
