"""
Centris CLI - Onboard Command

Interactive onboarding wizard for first-time setup.
"""

import click
import sys
import os
from pathlib import Path
from typing import Optional

from centris_sdk.cli.theme import theme, symbols, styled_success, styled_error, styled_warning
from centris_sdk.cli.wizard import Wizard, WizardCancelledError, note
from centris_sdk.cli.banner import emit_banner
from centris_sdk.cli.ui import panel, bullet_list, check_list, command_hint


SDK_VERSION = "1.1.0"


def _find_project_root() -> Optional[Path]:
    """Find the project root directory."""
    candidates = [
        Path.cwd(),
        Path.cwd().parent,
        Path(__file__).resolve().parent.parent.parent.parent.parent.parent,
    ]
    
    for candidate in candidates:
        if (candidate / "backend").exists() or (candidate / ".env.example").exists():
            return candidate
    
    return None


def _ensure_directory(path: Path) -> bool:
    """Ensure a directory exists."""
    try:
        path.mkdir(parents=True, exist_ok=True)
        return True
    except Exception:
        return False


def _write_env_file(path: Path, values: dict) -> bool:
    """Write or update a .env file."""
    try:
        # Read existing content
        existing = {}
        if path.exists():
            for line in path.read_text().split("\n"):
                line = line.strip()
                if line and not line.startswith("#") and "=" in line:
                    key, _, value = line.partition("=")
                    existing[key.strip()] = value.strip()
        
        # Merge with new values
        existing.update(values)
        
        # Write back
        lines = []
        lines.append("# Centris Configuration")
        lines.append("# Generated by `centris onboard`")
        lines.append("")
        
        # Group by prefix
        groups = {
            "LLM": [],
            "DEEPSEEK": [],
            "OPENAI": [],
            "ANTHROPIC": [],
            "GEMINI": [],
            "DEEPGRAM": [],
            "TRANSCRIPTION": [],
            "TTS": [],
            "SERVER": [],
            "OTHER": [],
        }
        
        for key, value in existing.items():
            placed = False
            for prefix in groups:
                if key.startswith(prefix):
                    groups[prefix].append(f"{key}={value}")
                    placed = True
                    break
            if not placed:
                groups["OTHER"].append(f"{key}={value}")
        
        for group_name, entries in groups.items():
            if entries:
                lines.append(f"# {group_name}")
                lines.extend(sorted(entries))
                lines.append("")
        
        path.write_text("\n".join(lines))
        return True
    except Exception:
        return False


@click.command("onboard")
@click.option("--skip-keys", is_flag=True, help="Skip API key configuration")
@click.option("--skip-extension", is_flag=True, help="Skip Chrome extension setup")
@click.pass_context
def onboard_command(ctx: click.Context, skip_keys: bool, skip_extension: bool) -> None:
    """
    Interactive setup wizard for Centris.
    
    Guides you through first-time configuration:
    
    \b
    - API key setup (DeepSeek, Deepgram, optional providers)
    - Chrome extension installation
    - Directory structure creation
    - Environment file setup
    
    Examples:
    
        centris onboard                 Full onboarding wizard
        
        centris onboard --skip-keys     Skip API key setup
    """
    # Emit banner
    emit_banner(SDK_VERSION)
    
    try:
        wiz = Wizard("Centris Setup Wizard")
        wiz.set_total_steps(5)
        wiz.intro()
        
        click.echo(theme.muted("This wizard will help you configure Centris for first-time use."))
        click.echo(theme.muted("Press Ctrl+C or type 'q' at any prompt to cancel.\n"))
        
        # Find project root
        project_root = _find_project_root()
        if not project_root:
            click.echo(styled_warning("Could not detect project root. Using current directory."))
            project_root = Path.cwd()
        
        env_values = {}
        
        # =========================================================================
        # Step 1: Check existing configuration
        # =========================================================================
        wiz.step("Checking existing configuration")
        
        env_file = project_root / ".env"
        has_env = env_file.exists()
        
        centris_dir = Path.home() / ".centris"
        has_centris_dir = centris_dir.exists()
        
        click.echo()
        click.echo(check_list([
            (".env file", has_env),
            ("~/.centris directory", has_centris_dir),
        ]))
        click.echo()
        
        if has_env:
            click.echo(theme.muted("Existing .env file found. New values will be merged."))
        
        # =========================================================================
        # Step 2: API Keys
        # =========================================================================
        wiz.step("Configure API Keys")
        
        if skip_keys:
            click.echo(theme.muted("Skipping API key configuration (--skip-keys)"))
        else:
            click.echo()
            click.echo(theme.muted("Centris requires API keys for LLM and audio services."))
            click.echo(theme.muted("Get keys from:"))
            click.echo(bullet_list([
                "DeepSeek: https://platform.deepseek.com/api_keys",
                "Deepgram: https://console.deepgram.com/",
                "OpenAI (optional): https://platform.openai.com/api-keys",
            ]))
            click.echo()
            
            # Required keys
            click.echo(theme.heading("Required Keys"))
            
            # DeepSeek
            existing_deepseek = os.environ.get("DEEPSEEK_API_KEY", "")
            if existing_deepseek:
                click.echo(f"  {theme.success(symbols.CHECK)} DeepSeek API key already set")
            else:
                deepseek_key = wiz.text(
                    "DeepSeek API Key",
                    placeholder="sk-...",
                )
                if deepseek_key:
                    env_values["DEEPSEEK_API_KEY"] = deepseek_key
            
            # Deepgram
            existing_deepgram = os.environ.get("DEEPGRAM_API_KEY", "")
            if existing_deepgram:
                click.echo(f"  {theme.success(symbols.CHECK)} Deepgram API key already set")
            else:
                deepgram_key = wiz.text(
                    "Deepgram API Key",
                    placeholder="...",
                )
                if deepgram_key:
                    env_values["DEEPGRAM_API_KEY"] = deepgram_key
            
            # Optional keys
            click.echo()
            if wiz.confirm("Configure optional API keys? (OpenAI, Anthropic, Gemini)", default=False):
                click.echo(theme.heading("Optional Keys"))
                click.echo(theme.muted("Press Enter to skip any key.\n"))
                
                openai_key = wiz.text("OpenAI API Key (optional)", default="", placeholder="sk-...")
                if openai_key:
                    env_values["OPENAI_API_KEY"] = openai_key
                
                anthropic_key = wiz.text("Anthropic API Key (optional)", default="", placeholder="sk-ant-...")
                if anthropic_key:
                    env_values["ANTHROPIC_API_KEY"] = anthropic_key
                
                gemini_key = wiz.text("Gemini API Key (optional)", default="", placeholder="...")
                if gemini_key:
                    env_values["GEMINI_API_KEY"] = gemini_key
        
        # =========================================================================
        # Step 3: LLM Provider Selection
        # =========================================================================
        wiz.step("Configure LLM Provider")
        
        click.echo()
        llm_provider = wiz.select(
            "Select your primary LLM provider",
            options=[
                {"value": "deepseek", "label": "DeepSeek", "hint": "Fast, affordable, excellent for coding"},
                {"value": "openai", "label": "OpenAI", "hint": "GPT-4 and GPT-3.5"},
                {"value": "anthropic", "label": "Anthropic", "hint": "Claude models"},
                {"value": "gemini", "label": "Gemini", "hint": "Google's Gemini models"},
            ],
            default="deepseek",
        )
        env_values["LLM_PROVIDER"] = llm_provider
        
        # =========================================================================
        # Step 4: Directory Setup
        # =========================================================================
        wiz.step("Setup Directories")
        
        click.echo()
        
        # Create ~/.centris directory structure
        dirs_to_create = [
            centris_dir,
            centris_dir / "connectors",
            centris_dir / "cache",
            centris_dir / "logs",
        ]
        
        for dir_path in dirs_to_create:
            if _ensure_directory(dir_path):
                click.echo(f"  {theme.success(symbols.CHECK)} Created {theme.path(str(dir_path))}")
            else:
                click.echo(f"  {theme.warn('!')} Could not create {theme.path(str(dir_path))}")
        
        # =========================================================================
        # Step 5: Write Configuration
        # =========================================================================
        wiz.step("Save Configuration")
        
        click.echo()
        
        if env_values:
            if _write_env_file(env_file, env_values):
                click.echo(f"  {theme.success(symbols.CHECK)} Saved configuration to {theme.path(str(env_file))}")
            else:
                click.echo(styled_error(f"Could not write to {env_file}"))
        else:
            click.echo(theme.muted("  No new configuration to save."))
        
        # =========================================================================
        # Chrome Extension
        # =========================================================================
        if not skip_extension:
            click.echo()
            click.echo(theme.heading("Chrome Extension"))
            click.echo()
            click.echo(theme.muted("The Centris Chrome extension enables browser automation."))
            click.echo()
            
            note(
                "Install the extension from:\n"
                "  chrome://extensions -> Load unpacked -> select 'extension' folder\n\n"
                "Or install from the Chrome Web Store (coming soon)",
                title="Extension Installation"
            )
        
        # =========================================================================
        # Completion
        # =========================================================================
        wiz.outro("Centris setup complete!")
        
        click.echo(theme.heading("Next Steps"))
        click.echo()
        click.echo(bullet_list([
            "Run `centris doctor` to verify your setup",
            "Run `centris start` to start the backend server",
            "Run `centris status` to check server status",
        ]))
        click.echo()
        click.echo(theme.muted("For more help, visit: https://docs.centris.ai"))
        click.echo()
        
    except WizardCancelledError:
        click.echo()
        click.echo(theme.muted("Setup cancelled."))
        sys.exit(1)
    except KeyboardInterrupt:
        click.echo()
        click.echo(theme.muted("Setup cancelled."))
        sys.exit(1)
