#!/usr/bin/env python3
# summary: Keep personal and work AI sign-ins separate.
"""Keep personal and work AI sign-ins separate, and choose the account for new sessions."""
import argparse
import contextlib
import fcntl
import hashlib
import json
import os
import re
import shlex
import shutil
import signal
import subprocess
import sys
from pathlib import Path

TOOLS = {
    # other_login: signing in with a browser on another device (Claude Code shows its link and asks for the code
    # by itself when there's no browser here)
    "claude": {"label": "Claude Code", "env": "CLAUDE_CONFIG_DIR", "login": ["auth", "login"], "other_login": ["auth", "login"],
               "other_hint": "Open the link shown below on your other device, then paste its code here.",
               "install": ("vendor", "claude-code")},
    "codex": {"label": "Codex (ChatGPT)", "env": "CODEX_HOME", "login": ["login"], "other_login": ["login", "--device-auth"],
              "other_hint": "On your other device, open the link shown below and type in the code shown with it.",
              "install": ("repo", "openai-codex")},
    "hermes": {"label": "Hermes", "env": "HERMES_HOME", "login": ["setup"], "install": ("aur", "hermes-agent")},
}
ROOT = Path.home() / ".local/share/starchaser/ai-accounts"
USAGE = Path.home() / ".local/state/starchaser/ai-usage"
SELF = Path(__file__).resolve()
NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9 _.-]{0,63}\Z")


class AccountError(Exception):
    pass


def valid_name(name):
    if not isinstance(name, str) or not NAME.fullmatch(name) or name != name.strip():
        raise AccountError("Use 1–64 letters, numbers, spaces, periods, underscores or hyphens; start with a letter or number.")
    return name


def private_dir(path):
    path.mkdir(mode=0o700, parents=True, exist_ok=True)
    if path.is_symlink() or not path.is_dir():
        raise AccountError("An account folder is a link or is unavailable. Nothing was changed.")
    path.chmod(0o700)


@contextlib.contextmanager
def registry_lock():
    private_dir(ROOT)
    with open(ROOT / ".lock", "a", encoding="utf-8") as handle:
        fcntl.flock(handle, fcntl.LOCK_EX)
        yield


def read_registry(tool):
    path = ROOT / (tool + ".json")
    try:
        data = json.loads(path.read_text())
        entries = data["accounts"]
        if data["version"] != 1 or not isinstance(entries, list) or not entries:
            raise ValueError
        if sum(a["home"] == "" for a in entries) != 1:
            raise ValueError
        for a in entries:
            valid_name(a["name"])
            if not isinstance(a["ready"], bool):
                raise ValueError
            if a["home"] != "":
                valid_name(a["home"])
        if len({a["name"].casefold() for a in entries}) != len(entries) or len({a["home"] for a in entries}) != len(entries):
            raise ValueError
        if not any(a["home"] == data["active"] and a["ready"] for a in entries):
            raise ValueError
        return data
    except FileNotFoundError:
        return {"version": 1, "active": "", "accounts": [{"name": "Personal", "home": "", "ready": True}]}
    except (ValueError, KeyError, TypeError, AccountError):
        raise AccountError("Couldn't read the account list. Restore its saved file before changing accounts.") from None


def save_registry(tool, data):
    path = ROOT / (tool + ".json")
    temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
    try:
        with open(temporary, "x", encoding="utf-8") as handle:
            json.dump(data, handle, indent=2)
            handle.write("\n")
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(temporary, path)
        fd = os.open(ROOT, os.O_RDONLY | os.O_DIRECTORY)
        try:
            os.fsync(fd)
        finally:
            os.close(fd)
    finally:
        temporary.unlink(missing_ok=True)


def find_account(data, name):
    valid_name(name)
    for account in data["accounts"]:
        if account["name"].casefold() == name.casefold():
            return account
    raise AccountError("No account has that name. Run starchaser ai account list to see the names.")


def not_installed(tool):
    """Software has no terminal search hit for these tools (QA 20261107-2018 007), so name the install command."""
    source, name = TOOLS[tool]["install"]
    return (f"Install {TOOLS[tool]['label']} from Software first, or run: "
            f"starchaser software run install {source} {name}")


def account_home(tool, account, must_exist=True):
    if not account["home"]:
        return None
    path = ROOT / tool / account["home"]
    if path.is_symlink() or path.parent.is_symlink() or path.resolve().parent != (ROOT / tool).resolve():
        raise AccountError("The account folder points somewhere else. Nothing was changed.")
    if must_exist and not path.is_dir():
        raise AccountError("The account folder is missing. Restore it before using this account.")
    return path


def binary(tool):
    # Skip our dispatcher even if PATH contains several links to it. Keep PATH
    # intact for child processes that launch a different AI tool.
    for folder in os.get_exec_path():
        candidate = Path(folder) / tool
        if candidate.is_file() and os.access(candidate, os.X_OK) and candidate.resolve().name != SELF.name:
            return str(candidate.absolute())
    return None


def sync_shims():
    private_dir(ROOT)
    private_dir(ROOT / "bin")
    for tool in TOOLS:
        link = ROOT / "bin" / tool
        own = link.is_symlink() and Path(os.readlink(link)).name == SELF.name
        available = binary(tool)
        if own and not available:
            link.unlink()
        elif available and (own or not (link.exists() or link.is_symlink())):
            if own and link.resolve() == SELF:
                continue
            temporary = link.with_name(f".{tool}.{os.getpid()}.tmp")
            try:
                temporary.symlink_to(SELF)
                os.replace(temporary, link)
            finally:
                temporary.unlink(missing_ok=True)


def lease_path(tool, account):
    return ROOT / ".leases" / (tool + "-" + ("account-" + account["home"] if account["home"] else "personal") + ".lock")


def lease(tool, account, exclusive=False):
    private_dir(ROOT / ".leases")
    handle = open(lease_path(tool, account), "a")
    try:
        fcntl.flock(handle, (fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) | fcntl.LOCK_NB)
    except BlockingIOError:
        handle.close()
        raise AccountError("This account has a running session or sign-in. Close it and try again.") from None
    return handle


def signin_path(tool, home):
    key = hashlib.sha256(str(home).encode()).hexdigest()[:20] if home else "personal"
    return ROOT / ".signins" / (tool + "-" + key + ".json")


def process_start(pid):
    try:
        # Records can survive a crash and restart; boot identity also prevents a
        # later boot's coincidentally matching PID/start tick from becoming a login.
        boot = Path("/proc/sys/kernel/random/boot_id").read_text().strip()
        tick = Path(f"/proc/{int(pid)}/stat").read_text().rsplit(")", 1)[1].split()[19]
        return boot + ":" + tick
    except (OSError, ValueError, TypeError, IndexError):
        return ""


def record_signin(tool, home, pid):
    start = process_start(pid)
    if not start:
        return  # A login that already exited has no pending task to cancel.
    path = signin_path(tool, home)
    private_dir(path.parent)
    temporary = path.with_suffix(f".{os.getpid()}.tmp")
    try:
        temporary.write_text(json.dumps({"pid": pid, "start": start}))
        temporary.chmod(0o600)
        os.replace(temporary, path)
    finally:
        temporary.unlink(missing_ok=True)


def signin_status(tool, home):
    try:
        record = json.loads(signin_path(tool, home).read_text())
        if type(record["pid"]) is int and record["pid"] > 1 and record["start"] \
                and process_start(record["pid"]) == record["start"]:
            return record
    except (OSError, ValueError, KeyError, TypeError):
        pass
    return None


def cancel_signin(tool, name):
    with registry_lock():
        account = find_account(read_registry(tool), name)
        home = account_home(tool, account)
        record = signin_status(tool, home)
        if record:
            # The descriptor pins the process while its start time is checked again.
            # Signal only our login child, never the browser or another terminal session.
            try:
                fd = os.pidfd_open(record["pid"])
                try:
                    if process_start(record["pid"]) == record["start"]:
                        signal.pidfd_send_signal(fd, signal.SIGINT)
                finally:
                    os.close(fd)
            except ProcessLookupError:
                pass
    return {"ok": True, "message": "Sign-in canceled. You can close its browser page."}


def launch(tool, args, home, managed=False, login=False, other_device=False, adding=True, track_signin=False):
    executable = binary(tool)
    if not executable:
        raise AccountError(not_installed(tool))
    env = os.environ.copy()
    variable = TOOLS[tool]["env"]
    pin = "STARCHASER_AI_" + tool.upper() + "_HOME"
    if tool == "hermes" and home is None and env.get(pin):
        # Returning to Personal from an added Hermes session also releases the
        # borrowed-credential locations that we pinned for that session.
        inherited = Path(env[pin])
        for key, suffix in (("HERMES_SHARED_AUTH_DIR", "shared"), ("CODEX_HOME", "codex"), ("CLAUDE_CONFIG_DIR", "claude")):
            if env.get(key) == str(inherited / suffix):
                env.pop(key)
    if home is None:
        env.pop(variable, None)
        env[pin] = ""  # Claude's implicit home also uses ~/.claude.json.
    else:
        env[variable] = str(home)
        env[pin] = str(home)
    if managed:
        # Never let an inherited provider key silently charge another account.
        for key in list(env):
            if key.endswith("_API_KEY") or key in ("ANTHROPIC_TOKEN", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_ACCESS_TOKEN"):
                env.pop(key)
        if tool == "codex":
            args = ["-c", 'cli_auth_credentials_store="file"', *args]
        if tool == "hermes":
            # Hermes can borrow other CLIs' credentials and share Nous auth.
            # These locations belong to this account too, never to Personal.
            env["HERMES_SHARED_AUTH_DIR"] = str(home / "shared")
            env["CODEX_HOME"] = str(home / "codex")
            env["CLAUDE_CONFIG_DIR"] = str(home / "claude")
            env.pop("HERMES_PROFILE", None)
    if login and other_device:
        # no browser opens here: the link and code above are the whole sign-in
        # Super+A signs in an account that already exists: there is nothing to add (QA 20261105-0801 001)
        # Ctrl+C copies the selected link here, so it cancels only with nothing selected (QA 20261106-0023 003)
        print("Sign in there with the account you want to " + ("add" if adding else "use here")
              + ". " + CANCEL_HINT + (" " + KEEP_NOTE if adding else ""), flush=True)
    elif login:
        print("Sign in with the account you want to add. A browser opens: check the account it shows before continuing. "
              "Paste a code here only if the page shows one. To cancel, press Ctrl+C or close this window."
              + (" " + KEEP_NOTE if adding else ""), flush=True)
    # Inherit the terminal directly: login codes and credentials never enter
    # Settings, a captured pipe, a log, or the account registry.
    command = [executable, *args]
    if os.environ.get("STARCHASER_ASK") == "1":
        from starchaser_ask_sandbox import command as sandbox_command
        auth_home = home or Path.home() / {"claude":".claude", "codex":".codex", "hermes":".hermes"}[tool]
        command = sandbox_command(executable, args, Path.cwd(), auth_home, variable)
    # Ctrl+C and terminal close target the terminal's foreground group. Keep
    # sign-in and browsers it opens outside that group, then forward cancellation
    # to the login PID alone so unrelated browser tabs stay open.
    signing_in = login or track_signin
    child = subprocess.Popen(command, env=env, start_new_session=signing_in)
    if login or track_signin:
        record_signin(tool, home, child.pid)
    previous = signal.signal(signal.SIGTERM, lambda *_: child.terminate())
    previous_hup = signal.signal(signal.SIGHUP, lambda *_: child.terminate()) if signing_in else None
    try:
        while True:
            try:
                code = child.wait()
                return code if code >= 0 else 128 - code
            except KeyboardInterrupt:
                child.send_signal(signal.SIGINT)
    finally:
        signal.signal(signal.SIGTERM, previous)
        if signing_in:
            signal.signal(signal.SIGHUP, previous_hup)
        if login or track_signin:
            signin_path(tool, home).unlink(missing_ok=True)


def run_account(tool, name, args):
    login = args == TOOLS[tool]["login"] or args == TOOLS[tool].get("other_login")
    with registry_lock():
        account = find_account(read_registry(tool), name)
        home = account_home(tool, account)
        handle = lease(tool, account, exclusive=login)
    with handle:
        if login:
            # terminal() already printed the correct browser/device instructions.
            return launch(tool, args, home, managed=home is not None, track_signin=True)
        return session(tool, args, account, home)


def dispatch(tool, args):
    variable = TOOLS[tool]["env"]
    pin = "STARCHASER_AI_" + tool.upper() + "_HOME"
    # Even an explicitly empty variable belongs to the caller. Do not consult
    # a broken registry or add flags when the caller provided a home.
    if variable in os.environ:
        executable = binary(tool)
        if not executable:
            raise AccountError(not_installed(tool))
        os.execv(executable, [executable, *args])
    if pin in os.environ:
        return launch(tool, args, Path(os.environ[pin]) if os.environ[pin] else None)
    with registry_lock():
        data = read_registry(tool)
        account = next(a for a in data["accounts"] if a["home"] == data["active"])
        home = account_home(tool, account)
        handle = lease(tool, account)
    with handle:
        return session(tool, args, account, home)


def session(tool, args, account, home):
    if explain_signin(tool, args, account, home):
        code = launch(tool, TOOLS[tool]["other_login"], home, managed=home is not None, login=True, other_device=True,
                      adding=False)
        # a canceled sign-in can exit 0: starting the tool then shows its own sign-in menu, outside Starchaser's
        # account list, so the window closes instead (QA 20261106-0023 003)
        if code or signed_out(tool, home):
            return code
    return launch(tool, args, home, managed=home is not None)


def explain_signin(tool, args, account, home):
    if not args and sys.stdin.isatty() and sys.stdout.isatty() and signed_out(tool, home):
        # Super+A on an account that never signed in starts the tool's own first-run screens: say which account
        # this is and what the sign-in asks for, before they take over the terminal
        other_device = False
        if "other_login" in TOOLS[tool]:
            try:
                other_device = subprocess.run(["starchaser", "webapp", "has-browser"], capture_output=True,
                                              timeout=10, check=False).returncode == 1
            except (OSError, subprocess.TimeoutExpired):
                pass
        hint = (TOOLS[tool]["other_hint"] + " " + MOUSE_COPY_HINT if other_device else
                "Sign in below: a browser opens for it. Paste a code here only if the page shows one.")
        state = ("needs to sign in to {} again: its saved sign-in stopped working." if tool == "codex"
                 and refused(tool, home, "auth.json") else "isn't signed in to {} yet.").format(TOOLS[tool]["label"])
        print(f"Starchaser: {account['name']} {state} {hint}", flush=True)
        if other_device:
            # the link stays on screen until the sign-in ends, and a notice in the corner would cover it
            # (QA 20261105-0823 003)
            return True
        # the tool's first screens clear the terminal, so that line can be gone before it's read: a notice says it
        # too, with the way to the account list. Best-effort: with no notification service there's just the line.
        try:
            subprocess.Popen(["sh", "-c", '[ "$(/bin/sh -c \'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi\' starchaser notify -w -a Starchaser -i dialog-information -A open="Open Settings > AI" "$0" "$1")" = open ] && exec starchaser settings ai Accounts',
                              f"{TOOLS[tool]['label']} isn't signed in yet",
                              f"The window that just opened starts {TOOLS[tool]['label']} as {account['name']}, and it "
                              "asks you to sign in first. To choose or add an account, open Settings > AI."],
                             stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                             start_new_session=True)
        except OSError:
            pass
    return False


def refused(tool, home, name):
    """True when Settings' last usage check found this Codex sign-in refused (its renewal failed too) and the sign-in
    file has not changed since: a sign-in that is still there but no longer works is signed out too."""
    path = home or Path.home() / ("." + tool)
    record_id = tool + "-" + (hashlib.sha256(home.name.encode()).hexdigest()[:20] if home else "personal")
    try:
        record = json.loads((USAGE / (record_id + ".json")).read_text())
        st = (path / name).stat()
    except (OSError, ValueError):
        return False
    # the same file metadata starchaser ai usage stores: a new sign-in since that check clears it
    return isinstance(record, dict) and record.get("authRequired") is True \
        and record.get("authStamp") == [[name, st.st_ino, st.st_mtime_ns, st.st_size]]


def signed_out(tool, home):
    """True when a known sign-in file is absent, Codex refused its sign-in, or Personal Codex reports no sign-in (it may
    use the keyring)."""
    if tool == "claude" and (home is not None or not any(k in os.environ for k in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"))):
        # Not refused(): Claude Code renews an expired sign-in itself when it starts.
        return not ((home or Path.home() / ".claude") / ".credentials.json").is_file()
    if tool == "codex":
        if refused(tool, home, "auth.json"):
            return True  # Super+A then explains and offers the other-device sign-in (QA 20261107-1411 003)
        if home is not None:
            return not (home / "auth.json").is_file()
        # Personal may keep its sign-in in the keyring; ask the installed tool rather than guessing from a file.
        executable = binary(tool)
        if executable:
            try:
                return subprocess.run([executable, "login", "status"], stdout=subprocess.DEVNULL,
                                      stderr=subprocess.DEVNULL, timeout=10, check=False).returncode == 1
            except (OSError, subprocess.TimeoutExpired):
                pass
    return False


def add(tool, name, other_device=False):
    valid_name(name)
    if other_device and "other_login" not in TOOLS[tool]:
        raise AccountError(OTHER_DEVICE_ONLY)
    if not binary(tool):
        raise AccountError(not_installed(tool))
    # no browser here: sign in from another device, as Settings > AI offers (not "A browser opens")
    if not other_device and "other_login" in TOOLS[tool]:
        try:
            other_device = subprocess.run(["starchaser", "webapp", "has-browser"], capture_output=True, check=False).returncode != 0
        except OSError:
            pass  # no way to ask: keep the browser sign-in
    with registry_lock():
        data = read_registry(tool)
        account = next((a for a in data["accounts"] if a["name"].casefold() == name.casefold()), None)
        if account and account["ready"]:
            raise AccountError("That account name is already in use. Choose another name.")
        if account is None:
            private_dir(ROOT / tool)
            home = ROOT / tool / name
            if home.exists() or home.is_symlink():
                raise AccountError("A folder already has that name. Choose another name; its files were left alone.")
            home.mkdir(mode=0o700)
            if tool == "codex":
                (home / "config.toml").write_text('cli_auth_credentials_store = "file"\n')
            account = {"name": name, "home": name, "ready": False}
            data["accounts"].append(account)
            save_registry(tool, data)  # A canceled sign-in can be retried in this same home.
        home = account_home(tool, account)
        handle = lease(tool, account, exclusive=True)
    with registry_lock():
        sync_shims()
    with handle:
        code = launch(tool, TOOLS[tool]["other_login" if other_device else "login"], home, managed=True, login=True,
                      other_device=other_device)
        if not code and signed_out(tool, home):
            code = 1  # it ended without saving a sign-in (canceled with Ctrl+C, or closed): not added
        if code:
            print("Sign-in did not finish. To try again, choose Finish sign-in in Settings > AI, or run: "
                  + retry_command(tool, account["name"]), file=sys.stderr)
            return code
        with registry_lock():
            data = read_registry(tool)
            next(a for a in data["accounts"] if a["home"] == account["home"])["ready"] = True
            save_registry(tool, data)
    follow_hooks()
    print("Account added. Choose Use when you want new sessions to start with it.")
    return 0


def follow_hooks():
    """With "Coding agents tell the taskbar when they're waiting for you" on, wire the new account's folder too, so its
    sessions report waiting like the original's. Best-effort: the account works without it."""
    agent = SELF.with_name("starchaser-agent")
    try:
        subprocess.run([str(agent) if agent.exists() else "starchaser agent", "hooks", "sync"], stdin=subprocess.DEVNULL,
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20, check=False)
    except (OSError, subprocess.TimeoutExpired):
        pass


def retry_command(tool, name):
    # the account's current name: after a rename its folder keeps the old one, and add finds it by name
    return f"starchaser ai account add {tool} {shlex.quote(name)}"


def home_in_use(tool, home):
    prefix = (TOOLS[tool]["env"] + "=").encode()
    for path in Path("/proc").glob("[0-9]*/environ"):
        try:
            for item in path.read_bytes().split(b"\0"):
                if item.startswith(prefix) and Path(os.fsdecode(item[len(prefix):])).resolve() == home.resolve():
                    return True
        except (OSError, ValueError):
            continue
    return False


def change(args):
    tool = args.tool
    with registry_lock():
        data = read_registry(tool)
        account = find_account(data, args.name)
        original = dict(account)
        if args.command == "use":
            if not account["ready"]:
                raise AccountError("Finish signing in first: choose Finish sign-in in Settings > AI, or run: "
                                   + retry_command(tool, account["name"]))
            account_home(tool, account)
            data["active"] = account["home"]
        elif args.command == "rename":
            valid_name(args.new_name)
            if any(a is not account and a["name"].casefold() == args.new_name.casefold() for a in data["accounts"]):
                raise AccountError("That account name is already in use.")
            account["name"] = args.new_name
        else:
            if not account["home"]:
                raise AccountError("The original account stays in its default home and can't be removed here.")
        if args.command != "remove":
            save_registry(tool, data)
            return {"ok": True, "message": "New sessions use this account. Running sessions keep theirs." if args.command == "use" else "Account renamed."}
    # Always require a positive answer, including when stdin is a pipe. The
    # Settings confirmation sends yes only after the person presses Remove.
    print("Remove this account's saved sign-in, settings and conversations? Type yes to remove: ", end="", file=sys.stderr, flush=True)
    if sys.stdin.readline().strip().lower() != "yes":
        raise AccountError("Removal canceled.")
    with registry_lock():
        data = read_registry(tool)
        account = find_account(data, args.name)
        if account != original:
            raise AccountError("The account changed while you were confirming. Review it and try again.")
        with lease(tool, account, exclusive=True):
            home = account_home(tool, account, must_exist=False)
            if home_in_use(tool, home):
                raise AccountError("This account has a running session. Close it and try again.")
            # A failed deletion leaves the entry visible for repair. Never
            # revoke tokens remotely: another session may still hold a grant.
            if home.exists():
                shutil.rmtree(home)
            data["accounts"].remove(account)
            was_active = data["active"] == account["home"]
            if was_active:
                data["active"] = ""
            save_registry(tool, data)
            # its lock file goes too (held here, so nothing else has it): a later account of that name starts clean
            lease_path(tool, account).unlink(missing_ok=True)
    original_name = next(a["name"] for a in data["accounts"] if a["home"] == "")
    return {"ok": True, "message": "Account removed." + (f" New sessions use {original_name}." if was_active else "")}


def folder(tool, account):
    """Where the account's sign-in and settings live, as a person would type it: a rename keeps the folder."""
    path = ROOT / tool / account["home"] if account["home"] else Path.home() / ("." + tool)
    return "~/" + str(path.relative_to(Path.home())) if path.is_relative_to(Path.home()) else str(path)


def listing(tool=None):
    rows = []
    with registry_lock():
        for key in ([tool] if tool else TOOLS):
            data = read_registry(key)
            rows.append({"tool": key, "label": TOOLS[key]["label"], "installed": bool(binary(key)),
                         "override": TOOLS[key]["env"] in os.environ,
                         "accounts": [{"name": a["name"], "active": a["home"] == data["active"],
                                       "personal": a["home"] == "", "ready": a["ready"], "folder": folder(key, a),
                                       "home": a["home"], "signingIn": bool(signin_status(key, account_home(key, a, must_exist=False)))}
                                      for a in data["accounts"]]})
    return rows


# The sign-in link is about 600 characters: say how to copy it for the other device, rather than retype it
# (QA 20261105-0823 001). Every sign-in window says it the same way, Super+A's too (QA 20261106-0806 001).
# Add saves the account before the sign-in so a canceled one can be retried in the same home (QA 20261107-2018 006)
KEEP_NOTE = "Canceling leaves the account listed as Sign-in unfinished; finish it later in Settings > AI, or remove it."
MOUSE_COPY_HINT = ("To copy the link, press Ctrl+Shift+Y, then the letter shown beside it "
                   "(or select it with the mouse and press Ctrl+C).")
# The window has no close button (close buttons are off by default) and the close key depends on the shortcut set,
# so name the key that cancels: Ctrl+C copies a selection, and with nothing selected it cancels (QA 20261106-0806 001)
CANCEL_HINT = "To cancel, press Ctrl+C with nothing selected."
OTHER_DEVICE_ONLY = "Sign-in on another device is available for Claude Code and Codex accounts."


def terminal(action, tool, name, other_device=False, if_signed_out=False):
    valid_name(name)
    if other_device and ("other_login" not in TOOLS[tool] or action == "run"):
        raise AccountError(OTHER_DEVICE_ONLY)
    if not binary(tool):
        raise AccountError(not_installed(tool))
    if action == "add":
        # a name already in use fails here, before a sign-in terminal opens and tells you to open its link (QA 20261107-1353 006)
        # A renamed account keeps its folder under the old name, and add() refuses a name whose folder is there
        with registry_lock():
            taken = next((a for a in read_registry(tool)["accounts"] if a["name"].casefold() == name.casefold()), None)
            folder_taken = taken is None and ((ROOT / tool / name).exists() or (ROOT / tool / name).is_symlink())
        if taken and taken["ready"]:
            raise AccountError("That account name is already in use. Choose another name.")
        if folder_taken:
            raise AccountError("A folder already has that name. Choose another name.")
    if if_signed_out:
        # Software's Continue account setup goes straight to sign-in after an install, but never signs an account
        # in again that already is (QA 20261105-0801 002)
        with registry_lock():
            account = find_account(read_registry(tool), name)
            home = account_home(tool, account)
        if account["ready"] and not signed_out(tool, home):
            print(json.dumps({"ok": True, "message": f"{account['name']} is already signed in.", "terminal": False}))
            return
    if action != "run" and not other_device:
        can_use_code = "other_login" in TOOLS[tool]
        check = "has-browser" if can_use_code else "require-browser"
        if subprocess.run(["starchaser", "webapp", check], capture_output=True, check=False).returncode != 0:
            if if_signed_out:
                # Continue account setup opens Accounts too, which offers a browser or another device first: no
                # device-code terminal on top of that choice (QA 20261106-1854 001)
                print(json.dumps({"ok": True, "message": "No web browser is installed. Choose how to sign in.",
                                  "terminal": False}))
                return
            if can_use_code:
                other_device = True
            else:
                raise AccountError("Sign-in needs a web browser. Install one from Software, then choose Sign in again.")
    # signin: sign an added account in again, in its own home
    command = {"add": [str(SELF), "add", tool, name, *(["--other-device"] if other_device else [])],
               "run": [str(SELF), "run", name, tool],
               "signin": [str(SELF), "run", name, tool, *TOOLS[tool]["other_login" if other_device else "login"]]}[action]
    # The window stays open to show how a sign-in ended, or why a session couldn't start; Ctrl+C (exit 130) and a
    # session that ended normally close it.
    command = ["bash", "-c", '"$0" "$@"; case "$1:$?" in *:130|run:0) ;; *) read -rsn1 -p "Press a key to close" ;; esac',
               *command]
    # add says how to cancel in its own intro (launch); signing an account in again says it here, so every sign-in
    # terminal does, in the same words: with a link to copy, Ctrl+C copies, so it cancels only with nothing selected
    # (QA 20261106-0249 001). Foot's Ctrl+C never copies, so the copy hint is Kitty's alone.
    kitty = shutil.which("kitty")
    intro = " ".join(([TOOLS[tool]["other_hint"], *([MOUSE_COPY_HINT] if kitty else [])] if other_device else [])
                     + ([CANCEL_HINT if other_device else "To cancel, press Ctrl+C or close this window."]
                        if action == "signin" else []))
    if intro:
        command[2] = f'printf "%s\\n" "{intro}"; ' + command[2]
    # Sign-in is a short dialog opened from floating Settings, so its window must float above it too.
    window_class = ("agent-" if action == "run" else "agent-signin-") + tool
    if kitty:
        command = ["starchaser", "terminal", "--class", window_class, "--title", TOOLS[tool]["label"] + " - " + name,
                   *(["-o", "confirm_os_window_close=0"] if action != "run" else []), "-e", *command]
    elif shutil.which("foot"):
        command = ["foot", "--app-id=" + window_class, "--title", TOOLS[tool]["label"] + " - " + name, "-e", *command]
    else:
        raise AccountError("Install Kitty or Foot from Software to open an account terminal.")
    subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                     stderr=subprocess.DEVNULL, start_new_session=True)
    print(json.dumps({"ok": True, "message": "Continue in the terminal that opens.", "terminal": True}))


def parser():
    p = argparse.ArgumentParser(prog="starchaser ai account", description=__doc__, epilog='Tools: claude, codex, hermes. Names with spaces need quotes. Examples: starchaser ai account list; starchaser ai account use claude "Work".')
    sub = p.add_subparsers(dest="command", required=True)
    s = sub.add_parser("list", help="list accounts and show which is selected for new sessions")
    s.add_argument("tool", choices=TOOLS, nargs="?")
    s.add_argument("--json", action="store_true")
    for command, help_text in (("use", "select an account for new sessions"),
                               ("add", "add an account and sign in"),
                               ("rename", "change an account's name"),
                               ("remove", "remove a saved account")):
        s = sub.add_parser(command, help=help_text)
        s.add_argument("tool", choices=TOOLS)
        s.add_argument("name")
        if command == "rename":
            s.add_argument("new_name")
        if command != "add":
            s.add_argument("--json", action="store_true")
        else:
            s.add_argument("--other-device", action="store_true", help="sign in using a browser on another device")
    s = sub.add_parser("run", help="start a session as a named account")
    s.add_argument("name")
    s.add_argument("tool", choices=TOOLS)
    s.add_argument("args", nargs=argparse.REMAINDER)
    s = sub.add_parser("cancel-signin", help="cancel this account's pending sign-in")
    s.add_argument("tool", choices=TOOLS)
    s.add_argument("name")
    s.add_argument("--json", action="store_true")
    s = sub.add_parser("terminal", help="open sign-in or a named session in a terminal")
    s.add_argument("action", choices=("add", "run", "signin"))
    s.add_argument("tool", choices=TOOLS)
    s.add_argument("name")
    s.add_argument("--other-device", action="store_true", help="sign in using a browser on another device (Claude Code, Codex)")
    s.add_argument("--if-signed-out", action="store_true", help="signin: open it only when the account isn't signed in")
    sub.add_parser("sync", help="refresh installed tool shims (setup and user refresh)")
    return p


def main():
    os.umask(0o077)
    try:
        invoked = Path(sys.argv[0]).name
        if invoked in TOOLS:
            return dispatch(invoked, sys.argv[1:])
        args = parser().parse_args()
        if args.command == "sync":
            with registry_lock():
                sync_shims()
        elif args.command == "terminal":
            terminal(args.action, args.tool, args.name, args.other_device, args.if_signed_out)
        elif args.command == "add":
            return add(args.tool, args.name, args.other_device)
        elif args.command == "run":
            return run_account(args.tool, args.name, args.args)
        elif args.command == "cancel-signin":
            result = cancel_signin(args.tool, args.name)
            print(json.dumps(result) if args.json else result["message"])
        elif args.command == "list":
            rows = listing(args.tool)
            if args.json:
                print(json.dumps(rows))
            else:
                for row in rows:
                    print(row["label"] + ("" if row["installed"] else " (not installed)"))
                    for a in row["accounts"]:
                        # the same file check Settings > AI uses; a tool that is not installed cannot be signed in
                        out = row["installed"] and a["ready"] and signed_out(row["tool"], None if a["personal"] else ROOT / row["tool"] / a["home"])
                        print("  " + a["name"] + ("  Selected for new sessions" if a["active"] else "") + ("  Sign-in unfinished" if not a["ready"] else "") + ("  Not signed in" if out else ""))
        else:
            result = change(args)
            print(json.dumps(result) if args.json else result["message"])
        return 0
    except AccountError as error:
        print(str(error), file=sys.stderr)
        if "--json" in sys.argv or (len(sys.argv) > 1 and sys.argv[1] == "terminal"):
            print(json.dumps({"ok": False, "errors": str(error)}))
        return 1
    except OSError:
        print("Couldn't open or save the account files, or start the AI tool. Check permissions and try again.", file=sys.stderr)
        return 1
    except KeyboardInterrupt:
        return 130


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