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

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

from second_opinion_mcp.credentials import CredentialManager, detect_backend

logger = logging.getLogger("second-opinion")

# 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": "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": "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": "https://openrouter.ai/keys",
        "key_prefix": "sk-or-",
    },
    "openai": {
        "name": "OpenAI (ChatGPT)",
        "description": "GPT-4o via OAuth login (free for ChatGPT Plus) or API key",
        "keyring_service": "second-opinion",
        "keyring_name": "openai",
        "key_hint": "https://platform.openai.com/api-keys",
        "key_prefix": "sk-",
        "supports_oauth": True,
    },
}

# 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 detect_installation_method() -> tuple[str, str | None]:
    """Detect how second-opinion-mcp was installed.

    Returns:
        tuple: (method, python_path) where method is 'pipx', 'pip', or 'unknown'
               and python_path is the path to Python executable if found.
    """
    home = os.path.expanduser("~")
    system = platform.system()

    # Check for pipx installation
    if system == "Windows":
        pipx_paths = [
            os.path.join(home, ".local", "pipx", "venvs", "second-opinion-mcp", "Scripts", "python.exe"),
            os.path.join(home, "pipx", "venvs", "second-opinion-mcp", "Scripts", "python.exe"),
            os.path.join(os.environ.get("LOCALAPPDATA", ""), "pipx", "venvs", "second-opinion-mcp", "Scripts", "python.exe"),
        ]
    else:
        pipx_paths = [
            os.path.join(home, ".local", "share", "pipx", "venvs", "second-opinion-mcp", "bin", "python3"),
            os.path.join(home, ".local", "share", "pipx", "venvs", "second-opinion-mcp", "bin", "python"),
            os.path.join(home, ".local", "pipx", "venvs", "second-opinion-mcp", "bin", "python3"),
        ]

    for path in pipx_paths:
        if os.path.exists(path):
            return "pipx", path

    # Check if we're running from a venv (pip install -e . or pip install)
    if hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix):
        return "pip", sys.executable

    # Unknown installation method
    return "unknown", sys.executable


def get_pipx_python_path() -> str | None:
    """Get the Python path from pipx venv if installed via pipx."""
    method, path = detect_installation_method()
    if method == "pipx":
        return path
    return None


def check_credential_storage_available() -> tuple[bool, str]:
    """Check if credential storage backend is available and working."""
    manager = CredentialManager()
    return manager.check_available()


def print_credential_storage_info():
    """Print information about the credential storage backend being used."""
    backend_type, backend_desc = detect_backend()
    system = platform.system()

    print()
    print("=" * 60)
    print("  Credential Storage")
    print("=" * 60)
    print()
    print(f"Backend: {backend_desc}")
    print()

    if backend_type == "file":
        print("Credentials are stored in ~/.second-opinion-config with SSH-style")
        print("permissions (600). This is the same security model used by SSH keys.")
    else:
        if system == "Windows":
            print("Credentials are stored in Windows Credential Manager.")
        elif system == "Darwin":
            print("Credentials are stored in macOS Keychain.")

    print()


def print_manual_setup_instructions(providers: list[str] | None = None, existing: dict[str, bool] | None = None):
    """Print instructions for manual credential setup on all platforms."""
    print()
    print("=" * 60)
    print("  Manual API Key Setup")
    print("=" * 60)
    print()

    # Detect installation method and backend
    install_method, python_path = detect_installation_method()
    backend_type, backend_desc = detect_backend()
    system = platform.system()

    print(f"Credential storage: {backend_desc}")
    print()
    print("IMPORTANT: You must configure at least 2 providers for the")
    print("'consensus' tool to work. Single-provider mode is limited.")
    print()

    target_providers = providers if providers else list(PROVIDERS.keys())

    # Show status if we have existing info
    if existing:
        configured = [p for p in target_providers if existing.get(p)]
        not_configured = [p for p in target_providers if not existing.get(p)]
        if configured:
            print(f"Already configured: {', '.join(configured)}")
        if not_configured:
            print(f"Need to configure: {', '.join(not_configured)}")
        print()

    # Determine which Python to use
    if install_method == "pipx" and python_path:
        python_cmd = python_path
    elif python_path:
        python_cmd = python_path
    else:
        python_cmd = "python3" if system != "Windows" else "python"

    # Print API key info for all providers
    print("-" * 60)
    print("API Key Sources:")
    print("-" * 60)
    for provider in target_providers:
        config = PROVIDERS[provider]
        status = ""
        if existing and existing.get(provider):
            status = " [CONFIGURED]"
        print(f"  {config['name']}{status}")
        print(f"    Get key at: {config['key_hint']}")
        if config.get("key_prefix"):
            print(f"    Key format: starts with '{config['key_prefix']}'")
        print()

    print("-" * 60)
    print("Store API Keys:")
    print("-" * 60)
    print()

    if backend_type == "file":
        # File backend - show direct file editing or Python commands
        config_file = "~/.second-opinion-config"
        print(f"Option 1: Edit {config_file} directly")
        print()
        print(f"  Create/edit {config_file} with content:")
        print()
        print('  {')
        print('    "credentials": {')
        print('      "deepseek": "sk-YOUR_DEEPSEEK_KEY",')
        print('      "moonshot": "YOUR_MOONSHOT_KEY",')
        print('      "openrouter": "sk-or-YOUR_OPENROUTER_KEY"')
        print('    }')
        print('  }')
        print()
        if system != "Windows":
            print("  Then set permissions: chmod 600 ~/.second-opinion-config")
        print()
        print("Option 2: Use Python commands")
        print()
        if install_method == "pipx":
            print(f"  # Using pipx environment: {python_path}")
        print()
        for provider in target_providers:
            config = PROVIDERS[provider]
            example_key = f"YOUR_{provider.upper()}_KEY"
            if config.get("key_prefix"):
                example_key = f"{config['key_prefix']}{example_key}"
            print(f"  # {config['name']}")
            print(f"  {python_cmd} -c \"from second_opinion_mcp.credentials import CredentialManager; CredentialManager().set('{provider}', '{example_key}')\"")
            print()
    else:
        # Keyring backend (Windows/macOS)
        if install_method == "pipx":
            print(f"# Using pipx environment: {python_path}")
            print()
        for provider in target_providers:
            config = PROVIDERS[provider]
            example_key = f"YOUR_{provider.upper()}_KEY"
            if config.get("key_prefix"):
                example_key = f"{config['key_prefix']}{example_key}"
            print(f"# {config['name']}")
            print(f"{python_cmd} -c \"import keyring; keyring.set_password('second-opinion', '{provider}', '{example_key}')\"")
            print()

    print("-" * 60)
    print("Verify Configuration:")
    print("-" * 60)
    print()
    if backend_type == "file":
        print(f"  {python_cmd} -c \"from second_opinion_mcp.credentials import CredentialManager; m=CredentialManager(); print('deepseek:', bool(m.get('deepseek'))); print('moonshot:', bool(m.get('moonshot'))); print('openrouter:', bool(m.get('openrouter')))\"")
    else:
        print(f"  {python_cmd} -c \"import keyring; print('deepseek:', bool(keyring.get_password('second-opinion', 'deepseek'))); print('moonshot:', bool(keyring.get_password('second-opinion', 'moonshot'))); print('openrouter:', bool(keyring.get_password('second-opinion', 'openrouter')))\"")

    print()
    print("-" * 60)
    print("Register with Claude Code:")
    print("-" * 60)
    print()

    if providers and len(providers) >= 1:
        providers_str = ",".join(providers)
    else:
        providers_str = "deepseek,moonshot"

    print(f"  claude mcp add -s user second-opinion -e SECOND_OPINION_PROVIDERS=\"{providers_str}\" -- second-opinion-mcp")
    print()


def check_existing_keys() -> dict[str, bool]:
    """Check which providers already have API keys configured.

    For OpenAI, also checks OAuth tokens (own + Codex CLI) as fallback.
    """
    manager = CredentialManager()
    result = manager.get_all_configured(list(PROVIDERS.keys()))

    # Check OAuth fallback for OpenAI
    if not result.get("openai"):
        try:
            from second_opinion_mcp.openai_auth import get_openai_token
            if get_openai_token():
                result["openai"] = True
        except Exception:
            logger.debug("OAuth fallback check failed for OpenAI", exc_info=True)

    return result


def count_configured_providers() -> int:
    """Count how many providers have API keys configured."""
    return sum(1 for v in check_existing_keys().values() if v)


def store_api_key(provider: str, key: str) -> tuple[bool, str]:
    """Store API key using platform-appropriate credential storage. Returns (success, error_message)."""
    manager = CredentialManager()
    try:
        manager.set(provider, key)
        return True, ""
    except Exception as e:
        return False, str(e)


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()

    # OpenAI accepts both standard API keys and OAuth tokens
    if provider == "openai":
        if key.startswith("sk-") and len(key) >= 20:
            return True, ""
        # OAuth JWT token: must have 3 dot-separated non-empty segments
        parts = key.split(".")
        if len(parts) == 3 and all(parts):
            return True, ""
        return False, "Key should start with 'sk-' (API key) or be a long OAuth token"

    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)
    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 print_client_instructions(configured_providers: list[str]):
    """Print setup instructions for all supported MCP clients."""
    _, backend_desc = detect_backend()

    print()
    print("=" * 60)
    print("  Client Setup Instructions")
    print("=" * 60)
    print()
    print(f"Credential storage: {backend_desc}")

    # Claude Code CLI
    print()
    print("CLAUDE CODE CLI:")
    print(f"  {get_registration_command(configured_providers)}")

    # Claude Desktop
    print()
    print("CLAUDE DESKTOP APP:")
    print("  Add to claude_desktop_config.json:")
    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(get_desktop_config(configured_providers))

    # OpenClaw / Other MCP clients
    print()
    print("OPENCLAW / OTHER MCP CLIENTS:")
    print("  OpenClaw uses mcporter for MCP server integration.")
    print("  See README for setup instructions:")
    print("  https://github.com/MarvinFS/second-opinion-mcp#openclaw")

    print()


def setup_wizard():
    """Interactive setup wizard for second-opinion-mcp."""
    print()
    print("=" * 60)
    print("  Second Opinion MCP - Setup Wizard")
    print("=" * 60)
    print()

    # Detect and show backend info
    backend_type, backend_desc = detect_backend()
    print(f"Credential storage: {backend_desc}")
    print()

    # Check credential storage availability
    storage_ok, storage_info = check_credential_storage_available()

    if not storage_ok:
        print(f"Credential storage error: {storage_info}")
        print()
        print("Choose 'Manual setup' to get CLI commands for manual configuration.")
        print()

        choice = questionary.select(
            "How would you like to proceed?",
            choices=[
                questionary.Choice("Manual setup (show CLI commands)", value="manual"),
                questionary.Choice("Exit", value="exit"),
            ],
            style=custom_style,
        ).ask()

        if choice == "manual" or choice is None:
            print_manual_setup_instructions()
        return

    print("This wizard will help you configure API keys for AI providers.")
    if backend_type == "file":
        print("Keys are stored in ~/.second-opinion-config with SSH-style permissions.")
    else:
        print("Keys are stored securely in your system credential manager.")
    print()

    # Check existing configuration
    existing = check_existing_keys()
    configured_count = sum(1 for v in existing.values() if v)
    configured = [p for p, has_key in existing.items() if has_key]
    not_configured = [p for p, has_key in existing.items() if not has_key]

    # Show current status
    print("Current status:")
    for provider, config in PROVIDERS.items():
        status = "configured" if existing.get(provider) else "not configured"
        print(f"  {config['name']}: {status}")
    print()

    # If 2+ providers already configured, offer quick path
    if configured_count >= 2:
        print(f"You have {configured_count} providers configured (minimum 2 required).")
        print()

        action = questionary.select(
            "What would you like to do?",
            choices=[
                questionary.Choice("Show registration command (ready to use)", value="register"),
                questionary.Choice("Add or update API keys", value="configure"),
                questionary.Choice("Manual setup (show CLI commands)", value="manual"),
            ],
            style=custom_style,
        ).ask()

        if action == "register":
            print()
            print(f"Credential storage: {backend_desc}")

            client_choice = questionary.select(
                "Which client will you use?",
                choices=[
                    questionary.Choice("Claude Code CLI (Recommended)", value="claude-code"),
                    questionary.Choice("Claude Desktop App", value="claude-desktop"),
                    questionary.Choice("OpenClaw / Other MCP Client", value="other"),
                    questionary.Choice("Show all client instructions", value="all"),
                ],
                style=custom_style,
            ).ask()

            if client_choice == "all":
                print_client_instructions(configured)
            elif client_choice == "claude-code":
                print()
                print("Register with Claude Code CLI:")
                print()
                print(f"  {get_registration_command(configured)}")
                print()
                print("Then restart Claude Code.")
            elif client_choice == "claude-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("Then restart Claude Desktop.")
            else:
                print()
                print("For OpenClaw or other MCP clients:")
                print("  OpenClaw uses mcporter for MCP server integration.")
                print("  See README for setup instructions:")
                print("  https://github.com/MarvinFS/second-opinion-mcp#openclaw")
            return

        elif action == "manual":
            print_manual_setup_instructions(list(PROVIDERS.keys()), existing)
            return

        # Fall through to configure flow

    elif configured_count == 1:
        print(f"Only {configured_count} provider configured. You need at least 2.")
        print("The 'consensus' tool requires multiple models to debate.")
        print()
    else:
        print("No providers configured yet. You need at least 2.")
        print()

    # Setup method selection
    setup_method = questionary.select(
        "Setup method:",
        choices=[
            questionary.Choice("Interactive (enter keys now)", value="interactive"),
            questionary.Choice("Manual (show CLI commands)", value="manual"),
        ],
        style=custom_style,
    ).ask()

    if setup_method is None:
        print("Setup cancelled.")
        return

    if setup_method == "manual":
        # Ask which providers they want to configure
        choices = [
            questionary.Choice(
                f"{config['name']}" + (" (configured)" if existing.get(provider) else ""),
                value=provider,
                checked=not existing.get(provider)  # Pre-check unconfigured ones
            )
            for provider, config in PROVIDERS.items()
        ]

        selected = questionary.checkbox(
            "Select providers to configure:",
            choices=choices,
            style=custom_style,
        ).ask()

        if not selected:
            selected = list(PROVIDERS.keys())

        print_manual_setup_instructions(selected, existing)
        return

    # Interactive setup - determine which providers to configure
    if not_configured:
        # Default: configure unconfigured providers
        choices = []
        for provider, config in PROVIDERS.items():
            label = config["name"]
            if existing.get(provider):
                label += " (configured)"
            # Pre-check unconfigured ones, or all if less than 2 configured
            should_check = not existing.get(provider)
            choices.append(questionary.Choice(label, value=provider, checked=should_check))

        # Calculate how many more we need
        needed = max(0, 2 - configured_count)

        selected = questionary.checkbox(
            f"Select providers to configure (need {needed} more for minimum 2):",
            choices=choices,
            style=custom_style,
            validate=lambda x: len(x) >= 1 or "Select at least one provider",
        ).ask()
    else:
        # All configured, but user wants to update
        choices = [
            questionary.Choice(f"{config['name']} (configured)", value=provider)
            for provider, config in PROVIDERS.items()
        ]

        selected = questionary.checkbox(
            "Select providers to update:",
            choices=choices,
            style=custom_style,
        ).ask()

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

    # Check if this will meet minimum requirement
    will_configure_new = len([p for p in selected if not existing.get(p)])
    total_after = configured_count + will_configure_new

    if total_after < 2 and will_configure_new > 0:
        print()
        print(f"WARNING: After configuring, you'll have {total_after} provider(s).")
        print("You need at least 2 providers for the 'consensus' tool.")
        print("With only 1 provider, only basic tools will be available.")
        proceed = questionary.confirm(
            "Continue anyway?",
            default=False,
            style=custom_style,
        ).ask()
        if not proceed:
            return setup_wizard()

    print()

    # Configure API keys
    keyring_error_shown = False
    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"  Get your key at: {config['key_hint']}")

        # OpenAI: offer OAuth login, Codex import, or API key
        if config.get("supports_oauth"):
            auth_method = questionary.select(
                "  Authentication method:",
                choices=[
                    questionary.Choice("Login with ChatGPT Plus (OAuth) (Recommended)", value="oauth"),
                    questionary.Choice("Import from Codex CLI", value="codex"),
                    questionary.Choice("Enter API key (pay-as-you-go)", value="apikey"),
                ],
                style=custom_style,
            ).ask()

            if auth_method == "oauth":
                from second_opinion_mcp.openai_auth import oauth_login
                success = oauth_login()
                if success:
                    continue
                else:
                    print("  OAuth login failed.")
                    fallback = questionary.confirm(
                        "  Try another method?",
                        default=True,
                        style=custom_style,
                    ).ask()
                    if not fallback:
                        continue
                    # Re-ask for method (without OAuth this time)
                    auth_method = questionary.select(
                        "  Alternative method:",
                        choices=[
                            questionary.Choice("Import from Codex CLI", value="codex"),
                            questionary.Choice("Enter API key (pay-as-you-go)", value="apikey"),
                        ],
                        style=custom_style,
                    ).ask()

            if auth_method == "codex":
                from second_opinion_mcp.openai_auth import get_openai_token, CODEX_AUTH_FILE
                token = get_openai_token()
                if token:
                    print(f"  Found valid token from Codex CLI ({CODEX_AUTH_FILE})")
                    print("  OpenAI will use Codex CLI auth at runtime.")
                    print("  Configured successfully.")
                    continue
                else:
                    print(f"  No valid token found in {CODEX_AUTH_FILE}")
                    print("  Run 'codex login' first, then re-run this setup.")
                    print()
                    fallback = questionary.confirm(
                        "  Enter an API key instead?",
                        default=True,
                        style=custom_style,
                    ).ask()
                    if not fallback:
                        continue

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

            if key is None:
                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

            success, store_error = store_api_key(provider, key.strip())
            if success:
                print("  Key stored successfully.")
                break
            else:
                print(f"  Error storing key: {store_error}")
                if not keyring_error_shown:
                    keyring_error_shown = True
                    print()
                    print("  Credential storage failed.")
                    show_manual = questionary.confirm(
                        "  Show manual setup instructions?",
                        default=True,
                        style=custom_style,
                    ).ask()
                    if show_manual:
                        print_manual_setup_instructions(selected, existing)
                        return
                break

    # Check final configuration
    final_existing = check_existing_keys()
    final_configured = [p for p, has_key in final_existing.items() if has_key]
    final_count = len(final_configured)

    print()
    print("=" * 60)
    print("  Setup Complete!")
    print("=" * 60)
    print()

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

    print(f"Configured providers: {', '.join(final_configured)} ({final_count} total)")

    if final_count < 2:
        print()
        print("WARNING: Only 1 provider configured. The 'consensus' tool requires 2+.")
        print("Run 'second-opinion-mcp setup' to add more providers.")
        print()
        return

    # Ask which client to show instructions for
    client_choice = questionary.select(
        "Which client will you use?",
        choices=[
            questionary.Choice("Claude Code CLI (Recommended)", value="claude-code"),
            questionary.Choice("Claude Desktop App", value="claude-desktop"),
            questionary.Choice("OpenClaw / Other MCP Client", value="other"),
            questionary.Choice("Show all client instructions", value="all"),
        ],
        style=custom_style,
    ).ask()

    if client_choice == "all":
        print_client_instructions(final_configured)
    elif client_choice == "claude-code":
        print()
        print("Register with Claude Code CLI:")
        print()
        print(f"  {get_registration_command(final_configured)}")
        print()
        print("Then restart Claude Code.")
    elif client_choice == "claude-desktop":
        print()
        print("Add this to your claude_desktop_config.json:")
        print()
        print(get_desktop_config(final_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("Then restart Claude Desktop.")
    else:
        print()
        print("For OpenClaw or other MCP clients:")
        print("  OpenClaw uses mcporter for MCP server integration.")
        print("  See README for setup instructions:")
        print("  https://github.com/MarvinFS/second-opinion-mcp#openclaw")

    print()
    print("Verifying setup...")
    print()
    verify_setup()


def verify_setup():
    """Verify installation by checking credentials and API connectivity."""
    import httpx
    from second_opinion_mcp import __version__

    print(f"second-opinion-mcp v{__version__}")
    print()

    # Show credential backend
    _, backend_desc = detect_backend()
    print(f"Credential backend: {backend_desc}")
    print()

    # Check which providers have credentials
    existing = check_existing_keys()
    configured = [p for p, has_key in existing.items() if has_key]

    if not configured:
        print("Providers: none configured")
        print()
        print("Run 'second-opinion-mcp setup' to configure providers.")
        return

    # Check OpenAI auth type for display
    openai_is_oauth = False
    if "openai" in configured:
        try:
            from second_opinion_mcp.openai_auth import get_openai_token
            if get_openai_token() is not None:
                openai_is_oauth = True
        except Exception:
            pass

    # Test endpoints per provider
    test_urls = {
        "deepseek": "https://api.deepseek.com/models",
        "moonshot": "https://api.moonshot.ai/v1/models",
        "openrouter": "https://openrouter.ai/api/v1/models",
        "openai": "https://api.openai.com/v1/models",
    }

    print("Providers:")
    ready_count = 0
    manager = CredentialManager()

    for provider in PROVIDERS:
        if provider not in configured:
            continue

        name = provider
        padded = f"  {name} " + "." * (16 - len(name))

        # Skip connectivity test for OpenAI OAuth (no simple test endpoint)
        if provider == "openai" and openai_is_oauth:
            print(f"{padded} credentials OK (OAuth)")
            ready_count += 1
            continue

        # Get the API key for connectivity test
        api_key = manager.get(provider)
        if not api_key:
            print(f"{padded} credentials missing")
            continue

        # Test API connectivity
        url = test_urls.get(provider)
        if not url:
            print(f"{padded} credentials OK")
            ready_count += 1
            continue

        try:
            resp = httpx.get(
                url,
                headers={"Authorization": f"Bearer {api_key}"},
                timeout=10.0,
            )
            status = "credentials OK, API reachable" if resp.status_code < 400 else f"credentials OK, API returned {resp.status_code}"
            print(f"{padded} {status}")
            ready_count += 1
        except httpx.TimeoutException:
            print(f"{padded} credentials OK, API timeout")
            ready_count += 1
        except httpx.ConnectError:
            print(f"{padded} credentials OK, API unreachable")

    print()
    provider_word = "provider" if ready_count == 1 else "providers"
    status = f"{ready_count} {provider_word} ready"

    if ready_count >= 2:
        print(f"Status: {status} (minimum 2 required)")
    elif ready_count == 1:
        print(f"Status: {status} (minimum 2 required, add more with 'second-opinion-mcp setup')")
    else:
        print("Status: no providers ready")
        print("Run 'second-opinion-mcp setup' to configure providers.")
        return

    print()
    print("Register with Claude Code:")
    print("  claude mcp add -s user second-opinion -- second-opinion-mcp")
    print()


if __name__ == "__main__":
    setup_wizard()
