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

from __future__ import annotations

import sys

import httpx
import yaml

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()
        accounts = c.get("/dashboard/accounts").json()
        vms = c.get("/dashboard/vms").json()
        providers = c.get("/dashboard/providers").json()
    except httpx.ConnectError:
        print(f"\033[31mCannot connect to proxy at {args.proxy}\033[0m")
        sys.exit(1)

    # Build YAML structure
    output = {
        "version": health.get("version", "?"),
        "proxy_url": args.proxy,
        "timestamp": None,  # Could add timestamp here
        "budget": {
            "daily_remaining_usd": round(budget.get("daily_remaining_usd", 0), 2),
            "daily_limit_usd": round(budget.get("daily_limit_usd", 0), 2),
            "monthly_remaining_usd": round(budget.get("monthly_remaining_usd", 0), 2),
            "monthly_limit_usd": round(budget.get("monthly_limit_usd", 0), 2),
        },
        "accounts": {
            "total": costs.get("accounts_count", 0),
            "active": costs.get("accounts_active", 0),
            "list": [
                {
                    "id": a.get("id"),
                    "name": a.get("name"),
                    "provider": a.get("provider"),
                    "daily_cost": round(a.get("daily_cost", 0), 4),
                    "monthly_cost": round(a.get("monthly_cost", 0), 4),
                    "requests_today": a.get("daily_requests", 0),
                }
                for a in accounts.get("accounts", [])
            ],
        },
        "vms": {
            "total": system.get("vms", {}).get("total", 0),
            "running": system.get("vms", {}).get("running", 0),
            "list": [
                {
                    "id": vm.get("id"),
                    "name": vm.get("name"),
                    "state": vm.get("state"),
                    "tool": vm.get("tool"),
                    "ip": vm.get("ip"),
                    "uptime_seconds": vm.get("uptime"),
                    "code_mount": vm.get("code_mount"),
                }
                for vm in vms.get("vms", [])
            ],
        },
        "providers": [
            {
                "name": p.get("name"),
                "models": p.get("model_count"),
                "has_key": p.get("has_key"),
            }
            for p in providers.get("providers", [])
        ],
        "costs": {
            "today_usd": round(costs.get("daily_total_usd", 0), 4),
            "month_usd": round(costs.get("monthly_total_usd", 0), 4),
            "total_requests": costs.get("total_requests", 0),
            "by_provider": costs.get("by_provider", {}),
        },
        "system": {
            "libvirt_available": system.get("libvirt", {}).get("libvirt", False),
            "qemu_available": system.get("libvirt", {}).get("qemu", False),
            "total_models": system.get("providers", {}).get("total_models", 0),
        },
    }

    if getattr(args, "format", None) == "yaml":
        print(yaml.dump(output, default_flow_style=False, sort_keys=False))
    else:
        # Human-readable format
        print(f"\033[1m=== Proxym Status ===\033[0m")
        print(f"  Version:  {output['version']}")
        print(f"  Budget:   ${output['budget']['daily_remaining_usd']:.2f}/day remaining, "
              f"${output['budget']['monthly_remaining_usd']:.2f}/month remaining")
        print(f"  Accounts: {output['accounts']['active']}/{output['accounts']['total']} active")
        print(f"  Costs:    ${output['costs']['today_usd']:.4f} today, "
              f"${output['costs']['month_usd']:.4f} this month")
        print(f"  Requests: {output['costs']['total_requests']} total")
        if output['costs']['by_provider']:
            print(f"  By provider: {', '.join(f'{k}=${v:.4f}' for k, v in output['costs']['by_provider'].items())}")
        if output['system']['libvirt_available']:
            print(f"  Libvirt:  ✓ available")
        if output['vms']['list']:
            print(f"  VMs:      {output['vms']['running']}/{output['vms']['total']} running")


def cmd_models(args):
    c = make_client(args.proxy, args.key)
    data = c.get("/v1/models").json()
    models = data.get("data", [])
    
    if getattr(args, "format", None) == "yaml":
        # YAML output
        output = {
            "models": [
                {
                    "id": m["id"],
                    "provider": m["owned_by"],
                    "input_cost_per_1m": m["input_cost_per_1m"],
                    "output_cost_per_1m": m["output_cost_per_1m"],
                    "context_window": m["context_window"],
                    "tier_range": m["tier_range"],
                }
                for m in models
            ],
            "count": len(models),
        }
        print(yaml.dump(output, default_flow_style=False, sort_keys=False))
    else:
        # Table output
        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"])
