import json
import sys
from pathlib import Path
from colorama import Fore, init
from m2h_ai.core import ask_ai
from m2h_ai.update import check_for_update

init(autoreset=True)

CONFIG_DIR = Path.home() / ".m2h-ai"
CONFIG_FILE = CONFIG_DIR / "config.json"


def banner():
    print(Fore.CYAN + "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
    print(Fore.GREEN + "   M2H AI CLI")
    print(Fore.YELLOW + "   Powered by M2H Web Solution")
    print(Fore.CYAN + "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")


def first_time_login():
    print(Fore.YELLOW + "🔐 OpenRouter API key required")
    key = input("Enter API key: ").strip()

    if not key.startswith("sk-or-"):
        print(Fore.RED + "❌ Invalid OpenRouter key")
        sys.exit(1)

    CONFIG_DIR.mkdir(exist_ok=True)
    with open(CONFIG_FILE, "w") as f:
        json.dump({"api_key": key}, f)

    print(Fore.GREEN + "✅ API key saved successfully!\n")


def run():
    if not CONFIG_FILE.exists():
        first_time_login()

    check_for_update()
    banner()

    while True:
        try:
            q = input(Fore.BLUE + "m2h-ai ❯ ").strip()

            if q.lower() in ("exit", "quit"):
                print(Fore.GREEN + "\n👋 Bye")
                break

            if not q:
                continue

            print(Fore.YELLOW + "\nThinking...\n")
            print(Fore.WHITE + ask_ai(q) + "\n")

        except KeyboardInterrupt:
            print(Fore.GREEN + "\n👋 Bye")
            break
