#!/usr/bin/env python3
"""Interactive setup wizard for second-opinion-mcp."""
import sys
import platform

try:
    import questionary
    from questionary import Style
except ImportError:
    print("Error: questionary not installed. Run: pip install questionary")
    sys.exit(1)

import keyring

# Provider configurations
PROVIDERS = {
    "deepseek": {
        "name": "DeepSeek V3.2",
        "description": "DeepSeek Reasoner with chain-of-thought reasoning",
        "keyring_service": "second-opinion",
        "keyring_name": "deepseek",
        "key_hint": "Get your key at https://platform.deepseek.com",
        "key_prefix": "sk-",
    },
    "moonshot": {
        "name": "Kimi K2.5 (Moonshot)",
        "description": "Moonshot AI's Kimi with thinking mode",
        "keyring_service": "second-opinion",
        "keyring_name": "moonshot",
        "key_hint": "Get your key at https://platform.moonshot.cn",
        "key_prefix": None,
    },
    "openrouter": {
        "name": "OpenRouter",
        "description": "Access 300+ models via unified API",
        "keyring_service": "second-opinion",
        "keyring_name": "openrouter",
        "key_hint": "Get your key at https://openrouter.ai/keys",
        "key_prefix": "sk-or-",
    },
}

# Custom style for questionary
custom_style = Style([
    ("qmark", "fg:cyan bold"),
    ("question", "bold"),
    ("answer", "fg:cyan"),
    ("pointer", "fg:cyan bold"),
    ("highlighted", "fg:cyan bold"),
    ("selected", "fg:green"),
])


def check_existing_keys() -> dict[str, bool]:
    """Check which providers already have API keys configured."""
    existing = {}
    for provider, config in PROVIDERS.items():
        try:
            key = keyring.get_password(config["keyring_service"], config["keyring_name"])
            existing[provider] = bool(key)
        except Exception:
            existing[provider] = False
    return existing


def store_api_key(provider: str, key: str) -> bool:
    """Store API key in system keyring."""
    config = PROVIDERS[provider]
    try:
        keyring.set_password(config["keyring_service"], config["keyring_name"], key)
        return True
    except Exception as e:
        print(f"Error storing key: {e}")
        return False


def validate_api_key(provider: str, key: str) -> tuple[bool, str]:
    """Basic validation of API key format."""
    if not key or not key.strip():
        return False, "API key cannot be empty"

    config = PROVIDERS[provider]
    key = key.strip()

    if config["key_prefix"] and not key.startswith(config["key_prefix"]):
        return False, f"Key should start with '{config['key_prefix']}'"

    if len(key) < 20:
        return False, "Key seems too short"

    return True, ""


def get_registration_command(selected_providers: list[str]) -> str:
    """Generate the registration command for Claude Code CLI."""
    providers_env = ",".join(selected_providers)

    if platform.system() == "Windows":
        return f'''claude mcp add -s user second-opinion -e SECOND_OPINION_PROVIDERS="{providers_env}" -- second-opinion-mcp'''
    else:
        return f'''claude mcp add -s user second-opinion -e SECOND_OPINION_PROVIDERS="{providers_env}" -- second-opinion-mcp'''


def get_desktop_config(selected_providers: list[str]) -> str:
    """Generate Claude Desktop configuration JSON."""
    providers_env = ",".join(selected_providers)

    return f'''{{
  "mcpServers": {{
    "second-opinion": {{
      "command": "second-opinion-mcp",
      "env": {{
        "SECOND_OPINION_PROVIDERS": "{providers_env}"
      }}
    }}
  }}
}}'''


def setup_wizard():
    """Interactive setup wizard for second-opinion-mcp."""
    print()
    print("=" * 60)
    print("  Second Opinion MCP - Setup Wizard")
    print("=" * 60)
    print()
    print("This wizard will help you configure API keys for AI providers.")
    print("Keys are stored securely in your system keyring.")
    print()

    # Check existing configuration
    existing = check_existing_keys()
    has_existing = any(existing.values())

    if has_existing:
        configured = [p for p, has_key in existing.items() if has_key]
        print(f"Already configured: {', '.join(configured)}")
        print()

    # Provider selection
    choices = []
    for provider, config in PROVIDERS.items():
        label = config["name"]
        if existing.get(provider):
            label += " (configured)"
        choices.append(questionary.Choice(label, value=provider, checked=existing.get(provider, False)))

    selected = questionary.checkbox(
        "Select providers to configure (at least 2 recommended):",
        choices=choices,
        style=custom_style,
        validate=lambda x: len(x) >= 1 or "Select at least one provider",
    ).ask()

    if not selected:
        print("Setup cancelled.")
        return

    if len(selected) < 2:
        print()
        print("Note: Using 2+ providers enables the 'consensus' tool for multi-model debates.")
        proceed = questionary.confirm(
            "Continue with single provider?",
            default=True,
            style=custom_style,
        ).ask()
        if not proceed:
            return setup_wizard()  # Restart

    print()

    # Configure API keys
    for provider in selected:
        config = PROVIDERS[provider]

        if existing.get(provider):
            update = questionary.confirm(
                f"{config['name']} already configured. Update API key?",
                default=False,
                style=custom_style,
            ).ask()
            if not update:
                continue

        print(f"\n{config['name']}")
        print(f"  {config['key_hint']}")

        while True:
            key = questionary.password(
                f"  Enter API key:",
                style=custom_style,
            ).ask()

            if key is None:  # User cancelled
                print("  Skipped.")
                break

            valid, error = validate_api_key(provider, key)
            if not valid:
                print(f"  {error}")
                retry = questionary.confirm("Try again?", default=True, style=custom_style).ask()
                if not retry:
                    break
                continue

            if store_api_key(provider, key.strip()):
                print("  Key stored successfully.")
            break

    # Generate registration commands
    print()
    print("=" * 60)
    print("  Setup Complete!")
    print("=" * 60)
    print()

    # Filter to providers that now have keys
    configured = []
    for provider in selected:
        try:
            key = keyring.get_password(
                PROVIDERS[provider]["keyring_service"],
                PROVIDERS[provider]["keyring_name"]
            )
            if key:
                configured.append(provider)
        except Exception:
            pass

    if not configured:
        print("No API keys were configured. Run 'second-opinion-mcp setup' to try again.")
        return

    print(f"Configured providers: {', '.join(configured)}")
    print()

    # Show registration command
    print("For Claude Code CLI, run:")
    print()
    print(f"  {get_registration_command(configured)}")
    print()

    # Show desktop config
    show_desktop = questionary.confirm(
        "Show Claude Desktop configuration?",
        default=False,
        style=custom_style,
    ).ask()

    if show_desktop:
        print()
        print("Add this to your claude_desktop_config.json:")
        print()
        print(get_desktop_config(configured))
        print()
        if platform.system() == "Windows":
            print("Location: %APPDATA%\\Claude\\claude_desktop_config.json")
        elif platform.system() == "Darwin":
            print("Location: ~/Library/Application Support/Claude/claude_desktop_config.json")
        else:
            print("Location: ~/.config/Claude/claude_desktop_config.json")

    print()
    print("Test the server with:")
    print("  second-opinion-mcp")
    print()
    print("The server will start and wait for input. Press Ctrl+C to stop.")
    print()


if __name__ == "__main__":
    setup_wizard()
