#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))

from account_registry import AccountRegistry, AccountRegistryKind, AuthorityMode
from authority_migration import MigrationError
from gateway_account_manager import LocalGatewayAccountManager, GatewayAccountState, gateway_account_state
from runtime_paths import runtime_dir


def _registry(tool: str) -> AccountRegistry:
    return AccountRegistry(base_dir=runtime_dir(), kind=AccountRegistryKind(tool))


def _account(registry: AccountRegistry, slug: str):
    return next((account for account in registry.list() if account.slug == slug), None)


def _finish(code: int, *, wait: bool) -> int:
    if wait:
        try:
            input("Press Enter to close…")
        except EOFError:
            pass
    return code


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(prog="systray-gateway")
    parser.add_argument("action", choices=("status", "migrate", "activate", "cancel"))
    parser.add_argument("--tool", required=True, choices=("codex", "claude"))
    parser.add_argument("--account", required=True)
    parser.add_argument("--wait", action="store_true", help="wait for Enter before closing")
    args = parser.parse_args(argv)

    registry = _registry(args.tool)
    if args.action == "status":
        slug = registry.resolve_profile_token(args.account)
        if slug is None:
            print("systray-gateway: account not found", file=sys.stderr)
            return _finish(2, wait=args.wait)
        try:
            binding = registry.authority_binding_for(slug)
        except KeyError:
            print("systray-gateway: account not found", file=sys.stderr)
            return _finish(2, wait=args.wait)
        if binding is None:
            state = GatewayAccountState.NATIVE
        elif binding.quiesced:
            state = GatewayAccountState.PAUSED
        elif binding.mode == AuthorityMode.SUBROUTER_DARK:
            state = GatewayAccountState.TESTING
        else:
            state = GatewayAccountState.ACTIVE
        payload = {"tool": args.tool, "account": slug, "state": state.value}
    else:
        account = _account(registry, args.account)
        if account is None:
            print("systray-gateway: account not found", file=sys.stderr)
            return _finish(2, wait=args.wait)
        try:
            manager = LocalGatewayAccountManager(registry)
            if args.action == "migrate":
                manager.stage(account)
                payload = manager.activate(manager.current(account.slug)).as_dict()
            elif args.action == "activate":
                payload = manager.activate(account).as_dict()
            else:
                payload = manager.cancel(account).as_dict()
        except (MigrationError, OSError, RuntimeError) as exc:
            print(f"systray-gateway: {exc}", file=sys.stderr)
            return _finish(1, wait=args.wait)
    print(json.dumps(payload, sort_keys=True, separators=(",", ":")))
    return _finish(0, wait=args.wait)


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