"""
Vigil Setup Wizard — Interactive first-time configuration.
Creates ~/.vigil/.env with the user's LLM provider and credentials.
"""

from pathlib import Path
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt

# Vigil config lives in the user's home directory
VIGIL_CONFIG_DIR = Path.home() / ".vigil"
VIGIL_ENV_FILE = VIGIL_CONFIG_DIR / ".env"

console = Console()

# Provider registry — add new providers here
PROVIDERS = {
    "groq": {
        "name": "Groq",
        "description": "Free cloud API (recommended)",
        "needs_key": True,
        "key_name": "GROQ_API_KEY",
        "key_url": "https://console.groq.com/keys",
        "default_model": "llama-3.3-70b-versatile",
        "model_env": "GROQ_MODEL",
    },
    "google": {
        "name": "Google Gemini",
        "description": "Free tier available",
        "needs_key": True,
        "key_name": "GOOGLE_API_KEY",
        "key_url": "https://aistudio.google.com/apikey",
        "default_model": "gemini-2.5-flash",
        "model_env": "GOOGLE_MODEL",
    },
    "ollama": {
        "name": "Ollama / LMStudio",
        "description": "Local & free (requires Ollama running)",
        "needs_key": False,
        "default_model": "llama3",
        "model_env": "OLLAMA_MODEL",
    },
    "openai": {
        "name": "OpenAI",
        "description": "Paid (GPT-4o)",
        "needs_key": True,
        "key_name": "OPENAI_API_KEY",
        "key_url": "https://platform.openai.com/api-keys",
        "default_model": "gpt-4o",
        "model_env": "OPENAI_MODEL",
    },
}


def run_setup_wizard() -> bool:
    """
    Interactive setup wizard. Prompts the user for their LLM provider
    and credentials, then saves to ~/.vigil/.env.
    
    Returns True if setup completed successfully.
    """
    console.print(Panel(
        "[bold cyan] 🛡️ Welcome to Vigil![/bold cyan]\n\n"
        "Vigil needs an LLM to verify security findings.\n"
        "Choose a provider below. You can change this later with [bold]vigil init[/bold].",
        title="First-Time Setup",
        style="cyan",
    ))

    # --- 1. Show provider options ---
    console.print("\n[bold]Available LLM Providers:[/bold]\n")
    provider_keys = list(PROVIDERS.keys())
    for i, key in enumerate(provider_keys, 1):
        p = PROVIDERS[key]
        console.print(f"  [bold cyan]{i}[/bold cyan]. {p['name']}  —  {p['description']}")

    # --- 2. Ask for provider ---
    choice = Prompt.ask(
        "\n[bold]Select provider (number)[/bold]",
        choices=[str(i) for i in range(1, len(provider_keys) + 1)],
        default="1",
    )
    selected_key = provider_keys[int(choice) - 1]
    provider = PROVIDERS[selected_key]

    config_lines = [
        "# Vigil Configuration",
        f"# Generated by vigil init",
        f"LLM_PROVIDER={selected_key}",
    ]

    # --- 3. Ask for API key (if cloud provider) ---
    if provider["needs_key"]:
        console.print(f"\n  📎 Get your free API key at: [link]{provider['key_url']}[/link]")
        api_key = Prompt.ask(f"  Enter your {provider['name']} API key")
        if not api_key.strip():
            console.print("[red]API key cannot be empty. Setup cancelled.[/red]")
            return False
        config_lines.append(f"{provider['key_name']}={api_key.strip()}")

    # --- 4. Ask for Ollama-specific settings ---
    if selected_key == "ollama":
        base_url = Prompt.ask(
            "  Ollama/LMStudio endpoint URL",
            default="http://localhost:11434",
        )
        config_lines.append(f"OLLAMA_BASE_URL={base_url}")

    # --- 5. Ask for model ---
    model = Prompt.ask(
        "  Model name",
        default=provider["default_model"],
    )
    config_lines.append(f"{provider['model_env']}={model}")

    # --- 6. Save config ---
    try:
        VIGIL_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
        VIGIL_ENV_FILE.write_text("\n".join(config_lines) + "\n", encoding="utf-8")
    except OSError as e:
        console.print(f"[red]Failed to save config: {e}[/red]")
        return False

    console.print(f"\n[bold green]Configuration saved to {VIGIL_ENV_FILE}[/bold green]")
    console.print("  Run [bold]vigil init[/bold] anytime to reconfigure.\n")
    return True


def is_configured() -> bool:
    """
    Check if Vigil has been configured through any of the supported methods:
    1. ~/.vigil/.env exists (user ran vigil init)
    2. LLM_PROVIDER env var is set (Docker / CI)
    3. .env exists in current directory (developer mode)
    """
    import os

    if VIGIL_ENV_FILE.exists():
        return True
    if os.environ.get("LLM_PROVIDER"):
        return True
    if Path(".env").exists():
        return True
    return False
