#!/usr/bin/env python3
"""CLI Setup Command for AgentOS - Configure API Keys"""

import os
from pathlib import Path

from rich.console import Console
from rich.panel import Panel
from rich.prompt import Confirm, Prompt
from rich.table import Table

console = Console(force_terminal=True)

# Config directory
CONFIG_DIR = Path.home() / ".agentos"
ENV_FILE = CONFIG_DIR / ".env"

# Available providers with their env var names
PROVIDERS = {
    "github": {
        "env_var": "GIT_HUB_TOKEN",
        "name": "GitHub Copilot",
        "description": "GitHub Personal Access Token for Copilot API",
        "url": "https://github.com/settings/tokens",
    },
    "gemini": {
        "env_var": "GEMINI_API_KEY",
        "name": "Google Gemini",
        "description": "Google AI Studio API Key",
        "url": "https://aistudio.google.com/apikey",
    },
    "openai": {
        "env_var": "OPENAI_API_KEY",
        "name": "OpenAI",
        "description": "OpenAI API Key for GPT models",
        "url": "https://platform.openai.com/api-keys",
    },
    "claude": {
        "env_var": "CLAUDE_API_KEY",
        "name": "Anthropic Claude",
        "description": "Anthropic API Key for Claude models",
        "url": "https://console.anthropic.com/settings/keys",
    },
    "cohere": {
        "env_var": "COHERE_API_KEY",
        "name": "Cohere",
        "description": "Cohere API Key",
        "url": "https://dashboard.cohere.com/api-keys",
    },
}


def load_current_env() -> dict:
    """Load current environment variables from .env file."""
    env_vars = {}
    if ENV_FILE.exists():
        with open(ENV_FILE, "r") as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith("#") and "=" in line:
                    key, value = line.split("=", 1)
                    env_vars[key.strip()] = value.strip()
    return env_vars


def save_env(env_vars: dict):
    """Save environment variables to .env file."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)

    # Add header comment
    lines = [
        "# AgentOS Configuration",
        "# Generated by 'agentos setup'",
        "# https://agentos.sodeom.com/",
        "",
        "PYTHONIOENCODING=utf-8",
        "",
    ]

    for key, value in env_vars.items():
        if key != "PYTHONIOENCODING":  # Already added above
            lines.append(f"{key}={value}")

    with open(ENV_FILE, "w") as f:
        f.write("\n".join(lines) + "\n")

    console.print(f"\n[green]✓[/green] Configuration saved to [cyan]{ENV_FILE}[/cyan]")


def mask_key(key: str) -> str:
    """Mask API key for display."""
    if not key or len(key) < 10:
        return "[dim]Not set[/dim]"
    return f"{key[:8]}...{key[-4:]}"


def cmd_setup(args=None):
    """Interactive setup wizard for API keys."""
    console.print(
        Panel.fit(
            "[bold cyan]🔧 AgentOS Setup Wizard[/bold cyan]\n\n"
            "Configure your LLM provider API keys.\n"
            "Keys are stored in [cyan]~/.agentos/.env[/cyan]",
            border_style="cyan",
        )
    )

    # Load current config
    current_env = load_current_env()

    # Show current status
    console.print("\n[bold]Current Configuration:[/bold]\n")

    table = Table(show_header=True, header_style="bold magenta")
    table.add_column("Provider", style="cyan")
    table.add_column("Status", style="green")
    table.add_column("API Key", style="dim")

    for provider_id, info in PROVIDERS.items():
        env_var = info["env_var"]
        current_value = current_env.get(env_var, "")
        status = (
            "[green]✓ Configured[/green]"
            if current_value
            else "[yellow]○ Not set[/yellow]"
        )
        table.add_row(info["name"], status, mask_key(current_value))

    console.print(table)
    console.print()

    # Ask what to configure
    console.print("[bold]What would you like to configure?[/bold]\n")
    console.print("  [cyan]1[/cyan] Configure all providers")
    console.print("  [cyan]2[/cyan] Configure a specific provider")
    console.print("  [cyan]3[/cyan] View current configuration")
    console.print("  [cyan]4[/cyan] Reset all configuration")
    console.print("  [cyan]0[/cyan] Exit\n")

    choice = Prompt.ask("Select option", choices=["0", "1", "2", "3", "4"], default="1")

    if choice == "0":
        console.print("[dim]Setup cancelled.[/dim]")
        return

    if choice == "3":
        # Already showed config above
        console.print("[green]Configuration displayed above.[/green]")
        return

    if choice == "4":
        if Confirm.ask("[yellow]⚠️  Reset all API keys?[/yellow]", default=False):
            save_env({})
            console.print("[green]✓ Configuration reset.[/green]")
        return

    if choice == "2":
        # Configure specific provider
        console.print("\n[bold]Select provider to configure:[/bold]\n")
        provider_list = list(PROVIDERS.keys())
        for i, pid in enumerate(provider_list, 1):
            console.print(f"  [cyan]{i}[/cyan] {PROVIDERS[pid]['name']}")

        provider_choice = Prompt.ask(
            "Select provider",
            choices=[str(i) for i in range(1, len(provider_list) + 1)],
        )
        providers_to_configure = [provider_list[int(provider_choice) - 1]]
    else:
        # Configure all
        providers_to_configure = list(PROVIDERS.keys())

    # Configure selected providers
    console.print()
    new_env = current_env.copy()

    for provider_id in providers_to_configure:
        info = PROVIDERS[provider_id]
        env_var = info["env_var"]
        current_value = current_env.get(env_var, "")

        console.print(
            Panel(
                f"[bold]{info['name']}[/bold]\n\n"
                f"{info['description']}\n\n"
                f"Get your key: [link={info['url']}]{info['url']}[/link]",
                border_style="blue",
                width=60,
            )
        )

        if current_value:
            console.print(f"Current: {mask_key(current_value)}")
            if not Confirm.ask("Update this key?", default=False):
                continue

        new_key = Prompt.ask(
            f"Enter {info['name']} API key",
            password=True,
            default="" if not current_value else None,
        )

        if new_key:
            new_env[env_var] = new_key
            console.print(f"[green]✓[/green] {info['name']} key saved\n")
        elif not current_value:
            console.print(f"[yellow]○[/yellow] {info['name']} skipped\n")

    # Save configuration
    if new_env != current_env:
        save_env(new_env)

        console.print(
            Panel(
                "[bold green]✓ Setup Complete![/bold green]\n\n"
                "Your API keys are now configured.\n"
                "Start chatting with: [cyan]agentos chat --provider <provider>[/cyan]",
                border_style="green",
            )
        )
    else:
        console.print("[dim]No changes made.[/dim]")


def cmd_setup_show(args=None):
    """Show current configuration status."""
    console.print(
        Panel.fit(
            "[bold cyan]🔧 AgentOS Configuration[/bold cyan]", border_style="cyan"
        )
    )

    current_env = load_current_env()

    table = Table(show_header=True, header_style="bold magenta")
    table.add_column("Provider", style="cyan", width=20)
    table.add_column("Env Variable", style="dim", width=20)
    table.add_column("Status", width=15)
    table.add_column("API Key", style="dim", width=25)

    configured_count = 0
    for provider_id, info in PROVIDERS.items():
        env_var = info["env_var"]
        current_value = current_env.get(env_var, "")
        if current_value:
            configured_count += 1
            status = "[green]✓ Ready[/green]"
        else:
            status = "[yellow]○ Not set[/yellow]"
        table.add_row(info["name"], env_var, status, mask_key(current_value))

    console.print(table)
    console.print(f"\n[dim]Config file: {ENV_FILE}[/dim]")
    console.print(
        f"[dim]Configured: {configured_count}/{len(PROVIDERS)} providers[/dim]"
    )

    if configured_count == 0:
        console.print(
            "\n[yellow]💡 Run [cyan]agentos setup[/cyan] to configure your API keys[/yellow]"
        )
