"""CLI commands: accounts list/add/costs — extracted from ctl.py."""

from __future__ import annotations

from proxym.cli._client import make_client, print_table


def cmd_accounts_list(args):
    c = make_client(args.proxy, args.key)
    data = c.get("/dashboard/accounts").json()
    accounts = data.get("accounts", [])
    if not accounts:
        print("No accounts configured. Use: proxym accounts add ...")
        return
    rows = []
    for a in accounts:
        rows.append({
            "id": a["id"],
            "name": a["name"],
            "provider": a["provider"],
            "plan": a.get("plan", ""),
            "active": "✓" if a["active"] else "✗",
            "budget": a.get("over_budget", False) and "OVER" or "ok",
            "daily$": f"${a['usage']['daily_cost']:.4f}",
            "total$": f"${a['usage']['total_cost']:.4f}",
            "reqs": str(a["usage"]["total_requests"]),
            "tools": str(len(a.get("tools", []))),
        })
    print_table(rows, ["id", "name", "provider", "plan", "active", "budget", "daily$", "total$", "reqs", "tools"])


def cmd_accounts_add(args):
    c = make_client(args.proxy, args.key)
    body = {
        "name": args.name,
        "provider": args.provider,
        "api_key": args.api_key or "",
        "email": args.email or "",
        "daily_budget_usd": args.daily_budget,
        "monthly_budget_usd": args.monthly_budget,
        "tags": args.tags.split(",") if args.tags else [],
    }
    response = c.post("/dashboard/accounts", json=body)
    result = response.json()
    sc = getattr(response, "status_code", 200)
    if isinstance(sc, int) and sc >= 400:
        detail = result.get("detail") or result.get("error") or "request failed"
        print(f"\033[31mError: {detail}\033[0m")
        raise SystemExit(1)
    print(f"\033[32mAccount created: {result.get('id')} ({result.get('name')})\033[0m")


def cmd_accounts_costs(args):
    c = make_client(args.proxy, args.key)
    data = c.get("/dashboard/costs/detailed").json()
    summary = data.get("summary", {})
    print("\033[1m=== Cost Summary ===\033[0m")
    print(f"  Today:    ${summary.get('daily_total_usd', 0):.4f}")
    print(f"  Month:    ${summary.get('monthly_total_usd', 0):.4f}")
    print(f"  Requests: {summary.get('total_requests', 0)}")
    print()
    accounts = data.get("accounts", [])
    if accounts:
        rows = []
        for a in accounts:
            budget = a.get("budget", {})
            rows.append({
                "name": a["name"],
                "provider": a.get("provider", "?"),
                "daily": f"${a['daily_cost']:.4f}",
                "monthly": f"${a['monthly_cost']:.4f}",
                "reqs": str(a.get("daily_requests", 0)),
                "remaining": f"${budget.get('daily_remaining_usd', 0):.2f}/d" if budget else "-",
                "status": "⚠ OVER" if a.get("over_budget") else "✓",
            })
        print_table(rows, ["name", "provider", "daily", "monthly", "reqs", "remaining", "status"])


def cmd_accounts_get(args):
    c = make_client(args.proxy, args.key)
    response = c.get(f"/dashboard/accounts/{args.account_id}")
    if response.status_code == 404:
        print(f"\033[31mAccount '{args.account_id}' not found.\033[0m")
        raise SystemExit(1)
    from proxym.cli._client import print_json
    print_json(response.json())


def cmd_accounts_delete(args):
    c = make_client(args.proxy, args.key)
    response = c.delete(f"/dashboard/accounts/{args.account_id}")
    if response.status_code == 404:
        print(f"\033[31mAccount '{args.account_id}' not found.\033[0m")
        raise SystemExit(1)
    result = response.json()
    if result.get("ok"):
        print(f"\033[32mAccount '{args.account_id}' deleted.\033[0m")
    else:
        print(f"\033[31mFailed to delete account '{args.account_id}'.\033[0m")
        raise SystemExit(1)


def cmd_accounts_bind_tool(args):
    c = make_client(args.proxy, args.key)
    body = {
        "tool_type": args.tool_type,
        "tool_name": args.tool_name,
    }
    if getattr(args, "vm_id", None):
        body["vm_id"] = args.vm_id
    if getattr(args, "project_path", None):
        body["project_path"] = args.project_path
    if getattr(args, "browser_profile", None):
        body["browser_profile"] = args.browser_profile
    response = c.post(f"/dashboard/accounts/{args.account_id}/bind-tool", json=body)
    if response.status_code == 404:
        print(f"\033[31mAccount '{args.account_id}' not found.\033[0m")
        raise SystemExit(1)
    result = response.json()
    if result.get("ok"):
        print(f"\033[32mTool '{args.tool_name}' bound to account '{args.account_id}'.\033[0m")
    else:
        print(f"\033[31mFailed to bind tool.\033[0m")
        raise SystemExit(1)
