"""CLI commands: serve, status, models — extracted from ctl.py."""

from __future__ import annotations

import sys

import httpx

from proxym.cli._client import make_client, print_table


def cmd_serve(args):
    """Start the proxy server (delegates to proxym.main:cli)."""
    from proxym.main import cli as server_cli
    sys.argv = ["proxym-server"]
    if args.host:
        sys.argv += ["--host", args.host]
    if args.port:
        sys.argv += ["--port", str(args.port)]
    if args.reload:
        sys.argv.append("--reload")
    server_cli()


def cmd_status(args):
    c = make_client(args.proxy, args.key)
    try:
        health = c.get("/health").json()
        budget = c.get("/v1/budget").json()
        costs = c.get("/dashboard/costs").json()
        system = c.get("/dashboard/system").json()
    except httpx.ConnectError:
        print(f"\033[31mCannot connect to proxy at {args.proxy}\033[0m")
        sys.exit(1)

    print(f"\033[1m=== Proxym Status ===\033[0m")
    print(f"  Version:  {health.get('version', '?')}")
    print(f"  Budget:   ${budget.get('daily_remaining_usd', 0):.2f}/day remaining, "
          f"${budget.get('monthly_remaining_usd', 0):.2f}/month remaining")
    print(f"  Accounts: {costs.get('accounts_active', 0)}/{costs.get('accounts_count', 0)} active")
    print(f"  Costs:    ${costs.get('daily_total_usd', 0):.4f} today, "
          f"${costs.get('monthly_total_usd', 0):.4f} this month")
    print(f"  Requests: {costs.get('total_requests', 0)} total")
    by = costs.get("by_provider", {})
    if by:
        print(f"  By provider: {', '.join(f'{k}=${v:.4f}' for k, v in by.items())}")
    libvirt = system.get("libvirt", {})
    if any(libvirt.values()):
        print(f"  Libvirt:  {'✓' if libvirt.get('libvirt') else '✗'} libvirt, "
              f"{'✓' if libvirt.get('qemu') else '✗'} qemu")


def cmd_models(args):
    c = make_client(args.proxy, args.key)
    data = c.get("/v1/models").json()
    models = data.get("data", [])
    rows = []
    for m in models:
        in_cost = m["input_cost_per_1m"]
        out_cost = m["output_cost_per_1m"]
        rows.append({
            "model": m["id"],
            "provider": m["owned_by"],
            "in$/1M": "FREE" if in_cost == 0 else f"${in_cost:.2f}",
            "out$/1M": "FREE" if out_cost == 0 else f"${out_cost:.2f}",
            "ctx": f"{m['context_window'] // 1000}K",
            "tiers": m["tier_range"],
        })
    print_table(rows, ["model", "provider", "in$/1M", "out$/1M", "ctx", "tiers"])
