"""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 [],
    }
    result = c.post("/dashboard/accounts", json=body).json()
    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["provider"],
                "daily": f"${a['daily_cost']:.4f}",
                "monthly": f"${a['monthly_cost']:.4f}",
                "reqs": str(a["daily_requests"]),
                "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"])
