"""AirClaw CLI"""

import os
import sys
import json
import argparse

BANNER = """
    _    _      _____ _               
   / \\  (_)_ __|  ___| | __ ___      __
  / _ \\ | | '__| |_  | |/ _` \\ \\ /\\ / /
 / ___ \\| | |  |  _| | | (_| |\\ V  V / 
/_/   \\_\\_|_|  |_|   |_|\\__,_| \\_/\\_/  

 Run OpenClaw with ZERO API cost — RabbitLLM + AirLLM
"""

MODELS = {
    "7b":    "mistralai/Mistral-7B-Instruct-v0.2",
    "8b":    "meta-llama/Meta-Llama-3-8B-Instruct",
    "13b":   "meta-llama/Llama-2-13B-chat-hf",
    "70b":   "meta-llama/Llama-2-70B-chat-hf",
    "qwen":  "Qwen/Qwen2.5-7B-Instruct",
    "deepseek": "deepseek-ai/deepseek-llm-7b-chat",
    "phi":   "microsoft/Phi-3-mini-4k-instruct",
}

DEFAULT_MODEL = MODELS["7b"]
DEFAULT_PORT  = 4096
DEFAULT_HOST  = "127.0.0.1"


def resolve_model(m):
    if m is None:
        return DEFAULT_MODEL
    return MODELS.get(m, m)


def cmd_start(args):
    from airclaw.server import start_server
    model = resolve_model(args.model)
    print(BANNER)
    start_server(model=model, port=args.port, host=args.host)


def cmd_patch(args):
    from airclaw.patch import patch_openclaw
    model = resolve_model(args.model) if args.model else "local-model"
    print(BANNER)
    ok = patch_openclaw(host=args.host, port=args.port, model=model, config_path=args.config)
    if ok:
        print("\n✅ Done!\n  1. airclaw start\n  2. openclaw restart\n")
    else:
        sys.exit(1)


def cmd_restore(args):
    from airclaw.patch import restore_backup
    restore_backup(args.config)


def cmd_status(args):
    try:
        import urllib.request
        with urllib.request.urlopen(f"http://127.0.0.1:{args.port}/health", timeout=3) as r:
            d = json.loads(r.read())
        status = d.get("status")
        backend = d.get("backend", "unknown")
        if status == "ready":
            print(f"✅ AirClaw running on :{args.port} — model READY ({backend})")
        elif status == "error":
            print(f"❌ Error: {d.get('error')}")
        else:
            print(f"⏳ AirClaw running on :{args.port} — model still loading...")
    except Exception:
        print(f"❌ AirClaw not running on :{args.port}\n   Start: airclaw start")


def cmd_install(args):
    print(BANNER)
    print("🚀 Full setup...\n")

    print("1/3 Installing dependencies...")
    backends = "rabbitllm airllm"
    deps = f"fastapi uvicorn pydantic torch {backends}"
    if os.system(f"pip install {deps} -q") != 0:
        os.system(f"pip install {deps} --break-system-packages -q")
    print("✅ Done\n")

    print("2/3 Patching OpenClaw config...")
    from airclaw.patch import patch_openclaw
    model = resolve_model(args.model) if args.model else "local-model"
    patch_openclaw(host=DEFAULT_HOST, port=args.port, model=model, config_path=args.config)

    print("""
3/3 Setup complete! 🎉

══════════════════════════════════════════
  Terminal 1:  airclaw start
  Terminal 2:  openclaw restart
  
  Done. Zero API cost. Forever.
══════════════════════════════════════════
""")


def main():
    parser = argparse.ArgumentParser(
        prog="airclaw",
        description="AirClaw — Run OpenClaw with zero API cost",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
commands:
  install    Full automated setup (do this first)
  start      Start local LLM server
  patch      Patch OpenClaw config
  restore    Restore original config
  status     Check if server is running

models:
  7b       Mistral-7B          4GB GPU  ← default
  8b       Llama-3-8B          6GB GPU
  13b      Llama-2-13B         8GB GPU
  70b      Llama-2-70B         4GB GPU (slow)
  qwen     Qwen2.5-7B          4GB GPU (newest)
  deepseek DeepSeek-7B         4GB GPU
  phi      Phi-3-mini          4GB GPU (fastest)
  or any HuggingFace model ID

examples:
  airclaw install
  airclaw start
  airclaw start --model qwen
  airclaw start --model deepseek
  airclaw patch --config ~/openclaw/config.json
  airclaw status
"""
    )

    sub = parser.add_subparsers(dest="command")

    for name in ["start", "patch", "install"]:
        p = sub.add_parser(name)
        p.add_argument("--model",  default=None)
        p.add_argument("--port",   default=DEFAULT_PORT, type=int)
        if name != "start":
            p.add_argument("--config", default=None)
        if name == "start":
            p.add_argument("--host", default=DEFAULT_HOST)
        if name == "patch":
            p.add_argument("--host", default=DEFAULT_HOST)

    p = sub.add_parser("restore")
    p.add_argument("--config", default=None)

    p = sub.add_parser("status")
    p.add_argument("--port", default=DEFAULT_PORT, type=int)

    args = parser.parse_args()

    {
        "start":   cmd_start,
        "patch":   cmd_patch,
        "restore": cmd_restore,
        "status":  cmd_status,
        "install": cmd_install,
    }.get(args.command, lambda _: (print(BANNER), parser.print_help()))(args)


if __name__ == "__main__":
    main()
