"""Interactive setup wizard for groknroll first run."""

import json
from pathlib import Path
from typing import Dict, Any, Optional

from rich.console import Console
from rich.prompt import Prompt, Confirm
from rich.panel import Panel
from rich.markdown import Markdown

console = Console()


def get_config_dir() -> Path:
    """Get groknroll configuration directory."""
    config_dir = Path.home() / ".groknroll"
    config_dir.mkdir(parents=True, exist_ok=True)
    return config_dir


def check_first_run() -> bool:
    """Check if this is the first time groknroll is being run."""
    config_file = get_config_dir() / "groknroll.json"
    setup_marker = get_config_dir() / ".setup_complete"

    # If config exists and setup marker exists, not first run
    if config_file.exists() and setup_marker.exists():
        return False

    return True


def run_setup(force: bool = False) -> Dict[str, Any]:
    """Run interactive setup wizard.

    Args:
        force: Force setup even if already configured

    Returns:
        Configuration dictionary
    """
    config_file = get_config_dir() / "groknroll.json"
    setup_marker = get_config_dir() / ".setup_complete"

    # Check if already set up
    if not force and config_file.exists() and setup_marker.exists():
        console.print("[yellow]Groknroll is already configured.[/yellow]")
        if not Confirm.ask("Run setup again?", default=False):
            # Load and return existing config
            with open(config_file, "r") as f:
                return json.load(f)

    # Welcome banner
    console.clear()
    console.print(Panel.fit(
        "[bold cyan]Welcome to Groknroll![/bold cyan]\n\n"
        "Let's get you set up in 60 seconds.\n"
        "You can change these settings later in ~/.groknroll/groknroll.json",
        border_style="cyan"
    ))
    console.print()

    config: Dict[str, Any] = {}

    # Step 1: Choose LLM Provider
    console.print("[bold]Step 1: Choose LLM Provider[/bold]")
    console.print("Groknroll works with multiple LLM providers:")
    console.print("  • [cyan]openai[/cyan]     - GPT-4o, o1, o3-mini (requires API key)")
    console.print("  • [cyan]anthropic[/cyan]  - Claude Opus 4, Sonnet 4 (requires API key)")
    console.print("  • [cyan]google[/cyan]     - Gemini 2.0 Flash, Pro (requires API key)")
    console.print("  • [cyan]local[/cyan]      - Ollama, LM Studio (free, runs locally)")
    console.print("  • [cyan]skip[/cyan]       - Configure later")
    console.print()

    provider = Prompt.ask(
        "Select provider",
        choices=["openai", "anthropic", "google", "local", "skip"],
        default="openai"
    )

    if provider != "skip":
        config["backend"] = provider

        # Step 2: Configure API Key or Local Model
        console.print()
        console.print("[bold]Step 2: Configure Provider[/bold]")

        if provider == "local":
            console.print("Local mode uses Ollama or LM Studio.")
            console.print("Make sure you have Ollama installed: https://ollama.ai")
            console.print()

            model_name = Prompt.ask(
                "Enter model name",
                default="llama3.2"
            )
            config["backend"] = "litellm"
            config["model_name"] = f"ollama/{model_name}"

            # Check if Ollama is running
            try:
                import httpx
                response = httpx.get("http://localhost:11434/api/tags", timeout=2)
                if response.status_code == 200:
                    console.print("[green]✓ Ollama is running[/green]")
                else:
                    console.print("[yellow]⚠ Ollama might not be running[/yellow]")
            except Exception:
                console.print("[yellow]⚠ Could not connect to Ollama[/yellow]")
                console.print("Start Ollama with: ollama serve")

        else:
            # Get API key
            env_var_name = f"{provider.upper()}_API_KEY"
            console.print(f"Enter your {provider.title()} API key.")
            console.print(f"(Get one from: {_get_provider_url(provider)})")
            console.print()

            api_key = Prompt.ask(
                f"{provider.title()} API key",
                password=True,
                default="",
            )

            if api_key:
                # Save to .env file
                env_file = get_config_dir() / ".env"
                env_content = ""

                # Load existing .env if present
                if env_file.exists():
                    env_content = env_file.read_text()

                # Update or append API key
                lines = env_content.split("\n")
                key_found = False
                for i, line in enumerate(lines):
                    if line.startswith(f"{env_var_name}="):
                        lines[i] = f"{env_var_name}={api_key}"
                        key_found = True
                        break

                if not key_found:
                    lines.append(f"{env_var_name}={api_key}")

                env_file.write_text("\n".join(lines))
                console.print(f"[green]✓ API key saved to {env_file}[/green]")

                # Set default model
                config["model_name"] = _get_default_model(provider)
            else:
                console.print("[yellow]Skipped API key configuration[/yellow]")
                console.print(f"You can set it later in {get_config_dir()}/.env")

    # Step 3: Optional Features
    console.print()
    console.print("[bold]Step 3: Optional Features[/bold]")

    # MCP
    if Confirm.ask("Enable MCP (Model Context Protocol) support?", default=False):
        config["mcp_enabled"] = True
        console.print("  [dim]MCP allows groknroll to use external tool servers[/dim]")
    else:
        config["mcp_enabled"] = False

    # LSP
    if Confirm.ask("Enable LSP (Language Server Protocol) support?", default=True):
        config["lsp_enabled"] = True
        console.print("  [dim]LSP provides code intelligence features[/dim]")
    else:
        config["lsp_enabled"] = False

    # Web UI
    if Confirm.ask("Enable web interface?", default=False):
        config["web_enabled"] = True
        config["web_port"] = int(Prompt.ask("Web interface port", default="8000"))
        console.print("  [dim]Access groknroll from your browser[/dim]")
    else:
        config["web_enabled"] = False

    # Step 4: Performance Settings
    console.print()
    console.print("[bold]Step 4: Performance Settings[/bold]")

    config["max_iterations"] = int(Prompt.ask(
        "Max iterations per completion",
        default="30"
    ))

    config["max_depth"] = int(Prompt.ask(
        "Max recursion depth",
        default="1"
    ))

    # Step 5: Save Configuration
    console.print()
    console.print("[bold]Step 5: Saving Configuration[/bold]")

    # Add default settings
    config.setdefault("version", "2.4.0")
    config.setdefault("permissions", {
        "read": "allow",
        "write": "ask",
        "bash": "ask",
        "edit": "ask",
    })

    # Save config
    with open(config_file, "w") as f:
        json.dump(config, indent=2, fp=f)

    # Mark setup as complete
    setup_marker.write_text("")

    console.print(f"[green]✓ Configuration saved to {config_file}[/green]")

    # Summary
    console.print()
    console.print(Panel.fit(
        "[bold green]Setup Complete! 🚀[/bold green]\n\n"
        f"Provider: {config.get('backend', 'Not configured')}\n"
        f"Model: {config.get('model_name', 'Not configured')}\n"
        f"Config: {config_file}\n\n"
        "Start coding with: [cyan]groknroll[/cyan]",
        border_style="green"
    ))

    return config


def _get_provider_url(provider: str) -> str:
    """Get signup URL for provider."""
    urls = {
        "openai": "https://platform.openai.com/api-keys",
        "anthropic": "https://console.anthropic.com/settings/keys",
        "google": "https://ai.google.dev/",
        "groq": "https://console.groq.com/keys",
    }
    return urls.get(provider, f"https://{provider}.com")


def _get_default_model(provider: str) -> str:
    """Get default model for provider."""
    models = {
        "openai": "gpt-4o",
        "anthropic": "claude-opus-4",
        "google": "gemini-2.0-flash-exp",
        "groq": "llama-3.3-70b-versatile",
    }
    return models.get(provider, "gpt-4o")


def show_quick_start():
    """Show quick start guide after setup."""
    console.print()
    console.print(Panel(
        Markdown("""
# Quick Start Guide

## Interactive REPL
```bash
groknroll
```

## One-off Task
```bash
groknroll build "Add tests to auth.py"
```

## Configuration
Edit config file: `~/.groknroll/groknroll.json`

Set API keys: `groknroll /connect`

## Slash Commands
- `/help` - Show help
- `/new` - New session
- `/save` - Save session
- `/agent <name>` - Switch agent
- `/connect` - Configure API keys

## Resources
- Documentation: https://docs.groknroll.dev
- GitHub: https://github.com/user/groknroll
- Discord: https://discord.gg/groknroll
        """),
        title="[bold cyan]Quick Start[/bold cyan]",
        border_style="cyan"
    ))
