"""Unified CLI for Proxym — AI proxy management.

Usage:
  proxym serve                     # start the proxy server
  proxym status                    # show system status
  proxym accounts list             # manage accounts
  proxym accounts add --name Work --provider anthropic --api-key sk-ant-...
  proxym accounts costs            # cost breakdown
  proxym vm create --tool windsurf --account work-anthropic
  proxym vm start windsurf-work
  proxym vm open windsurf-work     # SPICE viewer
  proxym vm ssh windsurf-work      # SSH into VM
  proxym vm switch windsurf-work --project other-project
  proxym browser list              # show host browser profiles
  proxym browser assign {profile} --account {id}
  proxym browser sync {vm_id}
  proxym models                    # list available models

Command handlers live in proxym.cli/ sub-modules:
  - system.py   — serve, status, models
  - accounts.py — accounts list/add/costs
  - vms.py      — vm list/create/action/switch/open/ssh/logs
  - browser.py  — browser list/assign/sync/snapshot
"""

from __future__ import annotations

import argparse

from proxym.config import get_settings
from proxym.cli.system import cmd_serve, cmd_status, cmd_models
from proxym.cli.accounts import cmd_accounts_list, cmd_accounts_add, cmd_accounts_costs
from proxym.cli.vms import (
    cmd_vm_list, cmd_vm_create, cmd_vm_action, cmd_vm_switch,
    cmd_vm_open, cmd_vm_ssh, cmd_vm_logs,
)
from proxym.cli.browser import (
    cmd_browser_list, cmd_browser_assign, cmd_browser_sync, cmd_browser_snapshot,
)


_VM_LIFECYCLE_ACTIONS = frozenset(("start", "stop", "pause", "resume", "snapshot"))

_TOP_DISPATCH = {"serve": cmd_serve, "status": cmd_status, "models": cmd_models}
_ACCT_DISPATCH = {"list": cmd_accounts_list, "add": cmd_accounts_add, "costs": cmd_accounts_costs}
_VM_DISPATCH = {
    "list": cmd_vm_list, "create": cmd_vm_create, "switch": cmd_vm_switch,
    "open": cmd_vm_open, "ssh": cmd_vm_ssh, "logs": cmd_vm_logs,
}
_BR_DISPATCH = {
    "list": cmd_browser_list, "assign": cmd_browser_assign,
    "sync": cmd_browser_sync, "snapshot": cmd_browser_snapshot,
}


def _dispatch(args, sub_parsers: dict):
    """Route parsed args to the correct command handler."""
    if args.command in _TOP_DISPATCH:
        _TOP_DISPATCH[args.command](args)
        return

    sub_cmd_attr = {"accounts": "acct_cmd", "vm": "vm_cmd", "browser": "br_cmd"}
    dispatch_map = {"accounts": _ACCT_DISPATCH, "vm": _VM_DISPATCH, "browser": _BR_DISPATCH}

    attr = sub_cmd_attr.get(args.command)
    table = dispatch_map.get(args.command)
    if not attr or not table:
        return

    sub_cmd = getattr(args, attr, None)
    if sub_cmd in table:
        table[sub_cmd](args)
    elif args.command == "vm" and sub_cmd in _VM_LIFECYCLE_ACTIONS:
        args.action = sub_cmd
        cmd_vm_action(args)
    else:
        sub_parsers[args.command].print_help()


# ── Main ─────────────────────────────────────────────────────

def main():
    settings = get_settings()

    parser = argparse.ArgumentParser(
        prog="proxym",
        description="Proxym — intelligent AI proxy with VM isolation",
    )
    parser.add_argument("--proxy", default=settings.default_proxy_url, help="Proxy URL")
    parser.add_argument("--key", default=settings.default_api_key, help="API key")

    sub = parser.add_subparsers(dest="command")

    # serve
    serve_p = sub.add_parser("serve", help="Start the proxy server")
    serve_p.add_argument("--host", default=None)
    serve_p.add_argument("--port", type=int, default=None)
    serve_p.add_argument("--reload", action="store_true")

    # status
    sub.add_parser("status", help="Show system status")

    # models
    sub.add_parser("models", help="List available models")

    # accounts
    acct = sub.add_parser("accounts", help="Manage accounts")
    acct_sub = acct.add_subparsers(dest="acct_cmd")
    acct_sub.add_parser("list", help="List accounts")
    acct_sub.add_parser("costs", help="Show cost breakdown")
    add_p = acct_sub.add_parser("add", help="Add account")
    add_p.add_argument("--name", required=True)
    add_p.add_argument("--provider", required=True)
    add_p.add_argument("--api-key", default="")
    add_p.add_argument("--email", default="")
    add_p.add_argument("--daily-budget", type=float, default=5.0)
    add_p.add_argument("--monthly-budget", type=float, default=60.0)
    add_p.add_argument("--tags", default="")

    # vm
    vm = sub.add_parser("vm", help="Manage VMs")
    vm_sub = vm.add_subparsers(dest="vm_cmd")
    vm_sub.add_parser("list", help="List VMs")

    create_p = vm_sub.add_parser("create", help="Create VM")
    create_p.add_argument("--name", default="")
    create_p.add_argument("--tool", default="")
    create_p.add_argument("--account", default="")
    create_p.add_argument("--mount", default="")
    create_p.add_argument("--project", default="")
    create_p.add_argument("--cpus", type=int, default=4)
    create_p.add_argument("--memory", type=int, default=6144)
    create_p.add_argument("--image", default="ubuntu-24.04")

    for action in ["start", "stop", "pause", "resume", "snapshot"]:
        act_p = vm_sub.add_parser(action, help=f"{action.title()} a VM")
        act_p.add_argument("vm_id")

    switch_p = vm_sub.add_parser("switch", help="Switch project in VM")
    switch_p.add_argument("vm_id")
    switch_p.add_argument("--project", required=True)

    open_p = vm_sub.add_parser("open", help="Open SPICE viewer")
    open_p.add_argument("vm_id")

    ssh_p = vm_sub.add_parser("ssh", help="SSH into VM")
    ssh_p.add_argument("vm_id")
    ssh_p.add_argument("--user", default="dev")

    logs_p = vm_sub.add_parser("logs", help="Show VM logs")
    logs_p.add_argument("vm_id")

    # browser
    br = sub.add_parser("browser", help="Manage browser profiles")
    br_sub = br.add_subparsers(dest="br_cmd")
    br_sub.add_parser("list", help="List host browser profiles")

    assign_p = br_sub.add_parser("assign", help="Assign profile to account")
    assign_p.add_argument("profile")
    assign_p.add_argument("--account", required=True)

    sync_p = br_sub.add_parser("sync", help="Sync browser profile host ↔ VM")
    sync_p.add_argument("vm_id")

    snap_p = br_sub.add_parser("snapshot", help="Save browser state from VM")
    snap_p.add_argument("vm_id")

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        return

    # ── Dispatch ──────────────────────────────────────────────
    _dispatch(args, sub_parsers={"accounts": acct, "vm": vm, "browser": br})


if __name__ == "__main__":
    main()
