import os
import questionary
import asyncio
import shutil
import importlib.resources
from typing import Optional
from .validator import validate_llm, validate_telegram
from ..config import settings

def run_wizard():
    """
    Runs an interactive wizard to configure Angel Claw.
    """
    print("\nWelcome to the Angel Claw Configuration Wizard!")
    print("This will help you set up your .env file for the first time.\n")

    # 1. LLM Provider & Key
    print("--- LLM Configuration ---")
    
    # Auto-detection
    detected_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("ANTHROPIC_API_KEY") or os.environ.get("GROQ_API_KEY")
    detected_provider = None
    if os.environ.get("OPENAI_API_KEY"): detected_provider = "OpenAI (gpt-4o, gpt-4o-mini)"
    elif os.environ.get("ANTHROPIC_API_KEY"): detected_provider = "Anthropic (claude-3-5-sonnet, etc.)"
    elif os.environ.get("GROQ_API_KEY"): detected_provider = "Groq"

    provider = questionary.select(
        "Which LLM provider do you want to use?",
        choices=[
            "OpenAI (gpt-4o, gpt-4o-mini)",
            "Anthropic (claude-3-5-sonnet, etc.)",
            "Ollama (local)",
            "Groq",
            "NVIDIA NIM",
            "Other (OpenAI-compatible)"
        ],
        default=detected_provider
    ).ask()

    if not provider: return

    default_model = "openai/gpt-4o-mini"
    default_base = None

    if "OpenAI" in provider and "Other" not in provider:
        default_model = "openai/gpt-4o-mini"
    elif "Anthropic" in provider:
        default_model = "anthropic/claude-3-5-sonnet-20240620"
    elif "Ollama" in provider:
        default_model = "ollama/llama3"
        default_base = "http://localhost:11434"
    elif "Groq" in provider:
        default_model = "groq/llama3-8b-8192"
    elif "NVIDIA" in provider:
        default_model = "nvidia/meta/llama3-70b-instruct"
        default_base = "https://integrate.api.nvidia.com/v1"

    model = questionary.text("Enter the model name (e.g., openai/gpt-4o):", default=default_model).ask()
    api_key = questionary.password("Enter your API Key:", default=detected_key or "").ask()
    api_base = questionary.text("Enter API Base URL (optional):", default=default_base or "").ask()
    if not api_base: api_base = None

    # Validate LLM
    print("🔄 Validating LLM connection...")
    success, msg = asyncio.run(validate_llm(model, api_key, api_base))
    if success:
        print(f"✅ {msg}")
    else:
        print(f"❌ Validation failed: {msg}")
        if not questionary.confirm("Do you want to continue anyway?").ask():
            return

    # 2. Telegram
    print("\n--- Optional Channels ---")
    setup_telegram = questionary.confirm("Do you want to set up Telegram?").ask()
    telegram_token = None
    if setup_telegram:
        telegram_token = questionary.password("Enter your Telegram Bot Token:").ask()
        print("🔄 Validating Telegram token...")
        t_success, t_msg = asyncio.run(validate_telegram(telegram_token))
        if t_success:
            print(f"✅ {t_msg}")
        else:
            print(f"❌ {t_msg}")

    # 3. WhatsApp
    setup_whatsapp = questionary.confirm("Do you want to enable WhatsApp?").ask()

    # 4. Write .env
    print("\n--- Saving Configuration ---")
    env_content = f"""# Angel Claw Configuration
# Generated by Wizard

# LLM Settings
MODEL={model}
MODEL_KEY={api_key}
"""
    if api_base:
        env_content += f"MODEL_BASE_URL={api_base}\n"

    env_content += f"\n# Channels\n"
    if telegram_token:
        env_content += f"TELEGRAM_TOKEN={telegram_token}\n"
    
    env_content += f"WHATSAPP_ENABLED={'True' if setup_whatsapp else 'False'}\n"

    # Preserving some defaults
    env_content += """
# Gateway Settings
HOST=0.0.0.0
PORT=8000
DEBUG=True

# Memory Settings
MEMORY_PERSIST_DIR=./vaults

# MCP Settings (Example everything server)
MCP_SERVERS='{"everything": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-everything"]}}'
"""

    if os.path.exists(".env"):
        shutil.copy(".env", ".env.bak")
        print("Created backup of existing .env as .env.bak")

    with open(".env", "w") as f:
        f.write(env_content)
    
    print("\n✅ Configuration saved to .env")
    print("You're ready to go!")
