"""Interactive onboarding wizard — helps users configure API keys and routing profile.

Run as a CLI entry point (``llm-router-onboard``) to launch the setup wizard.
The wizard reads any existing ``.env`` in the current directory, prompts the
user to add or update API keys for each supported provider, selects a routing
profile, and writes the final ``.env`` file.
"""

from __future__ import annotations

import sys
from pathlib import Path

PROVIDERS = {
    "GEMINI_API_KEY": {
        "name": "Google Gemini",
        "url": "https://aistudio.google.com/apikey",
        "models": "Gemini 2.0 Flash, Gemini 2.5 Pro",
    },
    "OPENAI_API_KEY": {
        "name": "OpenAI",
        "url": "https://platform.openai.com/api-keys",
        "models": "GPT-4o, GPT-4o-mini, o3",
    },
    "PERPLEXITY_API_KEY": {
        "name": "Perplexity",
        "url": "https://www.perplexity.ai/settings/api",
        "models": "Sonar, Sonar Pro (search-augmented)",
    },
}
"""Provider definitions for the onboarding wizard.

Each key is an environment variable name; the value dict contains the
human-readable provider name, the signup URL where the user can obtain an
API key, and a summary of available models.  The wizard iterates this dict
to present each provider in turn.
"""

PROFILES = {
    "budget": "Cheapest models — Gemini Flash, GPT-4o-mini, Sonar",
    "balanced": "Best quality/cost ratio — Gemini Pro, GPT-4o, Sonar Pro",
    "premium": "Best available — o3, Gemini 2.5 Pro, Sonar Pro",
}
"""Available routing profiles and their human-readable descriptions.

The selected profile is written to ``.env`` as ``LLM_ROUTER_PROFILE`` and
controls which model tier the router defaults to for each task type.
"""


def main() -> None:
    """Run the interactive CLI onboarding wizard for LLM Router.

    Flow:
        1. Read existing ``.env`` in the current directory (if present) to
           pre-populate current key values.
        2. For each provider in ``PROVIDERS``, show its name, available
           models, and signup URL.  If a key already exists, offer to keep
           it; otherwise prompt for a new key (or skip).
        3. Prompt for a routing profile selection from ``PROFILES``,
           defaulting to the previously configured profile or ``"balanced"``.
        4. Write all keys and the selected profile to ``.env`` with
           comments linking to each provider's signup page.
        5. Print a summary of configured vs. skipped providers and next
           steps.  Exit with code 1 if no providers were configured.
    """
    env_path = Path.cwd() / ".env"
    print("\n╔══════════════════════════════════════════╗")
    print("║        LLM Router — Setup Wizard         ║")
    print("╚══════════════════════════════════════════╝\n")

    # Load existing .env if present
    existing: dict[str, str] = {}
    if env_path.exists():
        for line in env_path.read_text().splitlines():
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                key, _, val = line.partition("=")
                existing[key.strip()] = val.strip()
        print(f"Found existing .env at {env_path}\n")

    keys: dict[str, str] = {}

    for env_var, info in PROVIDERS.items():
        current = existing.get(env_var, "")
        masked = f"{'*' * (len(current) - 4)}{current[-4:]}" if len(current) > 4 else ""

        print(f"── {info['name']} ──")
        print(f"   Models: {info['models']}")
        print(f"   Get key: {info['url']}")

        if masked:
            print(f"   Current: {masked}")
            keep = input("   Keep existing key? [Y/n]: ").strip().lower()
            if keep in ("", "y", "yes"):
                keys[env_var] = current
                print()
                continue

        key = input(f"   Enter {info['name']} API key (or press Enter to skip): ").strip()
        keys[env_var] = key
        print()

    # Profile selection
    print("── Routing Profile ──")
    for name, desc in PROFILES.items():
        print(f"   {name:10s} — {desc}")

    current_profile = existing.get("LLM_ROUTER_PROFILE", "balanced")
    profile = (
        input(f"\n   Choose profile [{current_profile}]: ").strip().lower()
        or current_profile
    )
    if profile not in PROFILES:
        print(f"   Invalid profile '{profile}', defaulting to 'balanced'")
        profile = "balanced"

    # Write .env
    lines = [
        "# LLM Router Configuration",
        "# Generated by llm-router-onboard",
        "",
    ]
    for env_var, info in PROVIDERS.items():
        lines.append(f"# {info['name']} ({info['url']})")
        lines.append(f"{env_var}={keys.get(env_var, '')}")
        lines.append("")

    lines.append(f"LLM_ROUTER_PROFILE={profile}")

    env_path.write_text("\n".join(lines) + "\n")

    # Summary
    configured = [info["name"] for var, info in PROVIDERS.items() if keys.get(var)]
    skipped = [info["name"] for var, info in PROVIDERS.items() if not keys.get(var)]

    print("\n╔══════════════════════════════════════════╗")
    print("║              Setup Complete!              ║")
    print("╚══════════════════════════════════════════╝")
    print(f"\n   .env written to: {env_path}")
    print(f"   Profile: {profile}")
    print(f"   Configured: {', '.join(configured) or 'none'}")
    if skipped:
        print(f"   Skipped: {', '.join(skipped)}")
    print("\n   You need at least 1 provider configured to use LLM Router.")

    if not configured:
        print("\n   ⚠ No API keys configured! Run this again when you have keys.")
        sys.exit(1)

    print("\n   Next: Add to Claude Code with `scripts/install.sh`")
    print("   Or manually add to ~/.claude.json mcpServers.\n")


if __name__ == "__main__":
    main()
