#!/usr/bin/env python3
"""Mint (or rotate) an MCPProxy agent token and save the secret to a file
without ever printing it.

  python3 mint_token.py --name notes-agent --profile notes-reader --expires 7d \
      --out ~/.config/mcpproxy/tokens/notes-agent

  python3 mint_token.py --regenerate --name notes-agent \
      --out ~/.config/mcpproxy/tokens/notes-agent

What it does:
  - The secret goes from `mcpproxy ... -o json` straight into --out. It is never
    written to stdout, stderr or the command line.
  - The destination is prepared before anything is created: a private temporary
    file (mode 600) in the same directory, which is created with mode 700 if it
    does not exist. A new token refuses to overwrite an existing --out file.
  - If a new token was created but could not be saved, the script revokes it and
    checks that the revoke worked. If it cannot confirm that, it says so and
    prints the command to run.
  - --regenerate replaces the file atomically. The old secret stops working at
    once, so the client needs the new one before its next request.
  - Runs for the same --out are serialised with a lock file. Do not rotate the
    same token from elsewhere at the same time.

POSIX only (macOS, Linux): it relies on file modes. Exit code 0 on success,
1 otherwise. Python 3.8+, standard library only.
"""
import argparse
import json
import os
import re
import subprocess
import sys
import tempfile

try:
    import fcntl
except ImportError:  # Windows: no advisory lock
    fcntl = None

NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,62}$")
TOKEN_RE = re.compile(r"^mcp_agt_[0-9a-f]{64}$")


def run(cli, args):
    """Run the mcpproxy CLI. stdout may hold the secret and is never printed."""
    try:
        proc = subprocess.run([cli] + args, capture_output=True, text=True)
    except OSError as err:
        return 127, "", f"cannot run {cli}: {err.strerror}"
    return proc.returncode, proc.stdout, proc.stderr


def last_line(text):
    lines = [ln for ln in text.strip().splitlines() if ln.strip()]
    return lines[-1] if lines else "no message"


def fail(msg):
    print(f"FAIL  {msg}")
    return 1


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("--name", required=True, help="token name (one per agent)")
    ap.add_argument("--profile", help="profile to pin the token to (required unless --regenerate)")
    ap.add_argument("--expires", help="expiry for a new token, e.g. 2h, 7d, 30d (default 7d)")
    ap.add_argument("--out", required=True, help="file to write the secret to")
    ap.add_argument("--regenerate", action="store_true",
                    help="rotate an existing token's secret (keeps its profile and expiry)")
    ap.add_argument("--force", action="store_true",
                    help="with --regenerate: overwrite --out even if it holds a different token")
    ap.add_argument("--mcpproxy", default="mcpproxy", help="path to the mcpproxy CLI")
    args = ap.parse_args()

    if os.name != "posix":
        return fail("this script relies on POSIX file modes to keep the secret private; "
                    "on Windows mint the token in the Web UI and store it in a secret manager")
    if not NAME_RE.match(args.name) or args.name.startswith("client-"):
        return fail("--name must be letters, digits, '-' or '_' and must not start with 'client-'")
    if not args.regenerate and not args.profile:
        return fail("--profile is required for a new token")
    if args.regenerate and (args.profile or args.expires):
        return fail("--regenerate keeps the token's profile and expiry: drop --profile/--expires, "
                    "or create a new token to change them")
    expires = args.expires or "7d"

    out = os.path.abspath(os.path.expanduser(args.out))
    parent = os.path.dirname(out)
    try:
        os.makedirs(parent, mode=0o700, exist_ok=True)
    except OSError as err:
        return fail(f"cannot create {parent}: {err.strerror}")
    if os.path.islink(out):
        return fail(f"{out} is a symlink; refusing to write through it")
    if os.path.isdir(out):
        return fail(f"{out} is a directory")
    if not args.regenerate and os.path.exists(out):
        return fail(f"{out} already exists; pick another --out or remove it first (nothing was created)")
    if args.regenerate and os.path.exists(out) and not args.force:
        # Refuse to overwrite a file that holds some other token's secret. The
        # stored prefix is short, so this catches a wrong path, not every clash.
        rc, shown, err = run(args.mcpproxy, ["token", "show", args.name, "-o", "json"])
        if rc != 0:
            return fail(f"mcpproxy token show failed: {last_line(err)} (nothing was changed)")
        try:
            prefix = json.loads(shown).get("token_prefix", "")
            with open(out) as fh:
                current = fh.read().strip()
        except (ValueError, AttributeError, OSError):
            prefix, current = "", ""
        if not prefix or not current.startswith(prefix):
            return fail(f"{out} does not hold the current secret of token {args.name}; "
                        f"check --out, or pass --force to overwrite it (nothing was changed)")

    # Serialise runs that target the same file. The lock file is a dotfile next
    # to --out; it is left in place afterwards (it is empty).
    lock_path = os.path.join(parent, "." + os.path.basename(out) + ".mintlock")
    lock_fd = None
    if fcntl is not None:
        try:
            lock_fd = os.open(lock_path, os.O_WRONLY | os.O_CREAT, 0o600)
            fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            if lock_fd is not None:
                os.close(lock_fd)
            return fail(f"another run is already writing {out}; nothing was created")

    # Prepare the destination BEFORE creating or rotating anything.
    try:
        tmp_fd, tmp = tempfile.mkstemp(prefix=".mint-", dir=parent)  # mode 600, unique
    except OSError as err:
        return fail(f"cannot write in {parent}: {err.strerror} (nothing was created)")
    if os.fstat(tmp_fd).st_mode & 0o077:
        # e.g. a FAT/exFAT or network mount that ignores file modes
        os.close(tmp_fd)
        os.unlink(tmp)
        if lock_fd is not None:
            os.close(lock_fd)
        return fail(f"{parent} does not keep files private (mode 600 is not honoured there); "
                    f"choose another --out (nothing was created)")

    def cleanup():
        try:
            os.unlink(tmp)
        except OSError:
            pass
        if lock_fd is not None:
            os.close(lock_fd)

    if args.regenerate:
        cmd = ["token", "regenerate", args.name, "-o", "json"]
    else:
        cmd = ["token", "create", "--name", args.name, "--profile", args.profile,
               "--expires", expires, "-o", "json"]
    code, stdout, stderr = run(args.mcpproxy, cmd)
    if code != 0:
        os.close(tmp_fd)
        cleanup()
        # stderr carries the CLI's reason, never the secret
        return fail(f"mcpproxy {' '.join(cmd[:2])} failed: {last_line(stderr)}")

    def undo(reason):
        """The CLI succeeded but the secret is not safely on disk."""
        cleanup()
        if args.regenerate:
            return fail(
                f"{reason}. The old secret no longer works and the new one was not saved. "
                f"Fix the cause, check that --out is the file you mean, then rotate again "
                f"with --regenerate --force (the file still holds the old, dead secret)."
            )
        rc, _, err = run(args.mcpproxy, ["token", "revoke", args.name])
        if rc == 0:
            return fail(f"{reason}. The new token was revoked; remove the record with: "
                        f"mcpproxy token delete {args.name}")
        return fail(
            f"{reason}. Revoking the new token ALSO failed ({last_line(err)}): it may still be "
            f"active. Run now: mcpproxy token revoke {args.name}"
        )

    try:
        token = json.loads(stdout).get("token", "")
    except (ValueError, AttributeError):
        token = ""
    if not isinstance(token, str) or not TOKEN_RE.match(token):
        os.close(tmp_fd)
        return undo("the CLI output did not contain a token in the expected format")

    installed = False
    try:
        with os.fdopen(tmp_fd, "w") as fh:
            fh.write(token)
            fh.flush()
            os.fsync(fh.fileno())
        if args.regenerate:
            os.replace(tmp, out)
        else:
            os.link(tmp, out)  # fails if --out appeared in the meantime
        installed = True
    except OSError as err:
        return undo(f"could not save the secret to {out}: {err.strerror}")
    except KeyboardInterrupt:
        if not installed:
            return undo(f"interrupted before the secret was saved to {out}")
        # the secret is on disk: fall through and finish normally

    cleanup()
    print(f"OK    token {args.name} {'regenerated' if args.regenerate else 'created'}")
    print(f"      prefix  {token[:12]}")
    print(f"      saved   {out} (mode 600)")
    print(f"      details mcpproxy token show {args.name}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
