"""CLI commands: browser list/assign/sync/snapshot — extracted from ctl.py."""

from __future__ import annotations

import sys

from proxym.cli._client import make_client, print_table


def cmd_browser_list(args):
    """List detected browser profiles on the host."""
    try:
        from proxym.virt.browser_profiles import detect_all_profiles
    except ImportError:
        print("\033[31mBrowser profiles module not available.\033[0m")
        sys.exit(1)
    profiles = detect_all_profiles()
    if not profiles:
        print("No browser profiles detected.")
        return
    rows = []
    for p in profiles:
        rows.append({
            "browser": p.browser,
            "name": p.name,
            "path": str(p.path)[:50],
            "size": f"{p.size_mb:.1f}MB",
            "sessions": "✓" if p.has_sessions else "✗",
            "accounts": ", ".join(p.accounts_detected[:3]) or "-",
        })
    print_table(rows, ["browser", "name", "path", "size", "sessions", "accounts"])


def cmd_browser_assign(args):
    """Assign a browser profile to an account."""
    c = make_client(args.proxy, args.key)
    result = c.post(f"/dashboard/accounts/{args.account}/bind-tool", json={
        "tool_type": "browser",
        "tool_name": f"browser-{args.profile}",
        "browser_profile": args.profile,
    }).json()
    if result.get("ok"):
        print(f"\033[32mProfile '{args.profile}' assigned to account {args.account}\033[0m")
    else:
        print("\033[31mFailed to assign profile\033[0m")


def _vm_browser_action(args, endpoint: str, ok_msg: str, fail_msg: str):
    """Post to a VM browser endpoint and print result."""
    c = make_client(args.proxy, args.key)
    result = c.post(f"/dashboard/vms/{args.vm_id}/{endpoint}").json()
    if result.get("ok"):
        print(f"\033[32m{ok_msg} {args.vm_id}\033[0m")
    else:
        print(f"\033[31m{fail_msg}\033[0m")


def cmd_browser_sync(args):
    """Sync browser profile host ↔ VM."""
    _vm_browser_action(args, "browser-sync", "Browser profile synced for VM", "Failed to sync browser profile")


def cmd_browser_snapshot(args):
    """Save browser state from VM as snapshot."""
    _vm_browser_action(args, "browser-snapshot", "Browser snapshot saved for VM", "Failed to snapshot browser")
