"""First-run setup wizard for Tribunal.

Runs on first launch when ~/.tribunal/ directory does not exist.
Shows a Rich-powered wizard to:
1. Check environment (Python, Node.js, claude binary)
2. Check Claude API access
3. Offer vault installation
4. Offer /sync

Skipped if --headless flag is set or ~/.tribunal/ already exists.
"""

from __future__ import annotations

import shutil
import subprocess
import sys
from pathlib import Path

SKILLFIELD_HOME = Path.home() / ".tribunal"


def is_first_run() -> bool:
    """Return True if this is the first run (no ~/.tribunal/ dir)."""
    return not SKILLFIELD_HOME.exists()


def _has_rich() -> bool:
    try:
        import importlib
        importlib.import_module("rich")
        return True
    except ImportError:
        return False


def run_wizard(headless: bool = False) -> None:
    """Run the first-run setup wizard.

    Safe to call unconditionally — exits immediately if not first run
    or if --headless mode is active.
    """
    if headless or not is_first_run():
        return

    if not _has_rich():
        _run_plain_wizard()
        return

    _run_rich_wizard()


def _check_env() -> list[tuple[str, bool, str]]:
    """Check environment prerequisites.

    Returns list of (label, ok, detail) tuples.
    """
    checks = []

    # Python version
    major, minor = sys.version_info[:2]
    py_ok = major >= 3 and minor >= 10
    checks.append(("Python 3.10+", py_ok, f"Python {major}.{minor}"))

    # Node.js
    node = shutil.which("node")
    node_ok = node is not None
    node_version = ""
    if node_ok:
        try:
            out = subprocess.check_output(["node", "--version"], text=True, timeout=5).strip()
            node_version = out
        except Exception:
            node_version = "found"
    checks.append(("Node.js", node_ok, node_version if node_ok else "not found"))

    # claude binary
    claude = shutil.which("claude")
    if not claude:
        from pathlib import Path
        npm_global = Path.home() / ".npm-global" / "bin" / "claude"
        if npm_global.exists():
            claude = str(npm_global)
    claude_ok = claude is not None
    checks.append(("claude CLI", claude_ok, claude if claude_ok else "not found — run: npm install -g @anthropic-ai/claude-code"))

    # ANTHROPIC_API_KEY
    import os
    api_key = os.environ.get("ANTHROPIC_API_KEY", "")
    key_ok = bool(api_key)
    checks.append(("ANTHROPIC_API_KEY", key_ok, "set" if key_ok else "not set — export ANTHROPIC_API_KEY=sk-ant-..."))

    return checks


def _run_rich_wizard() -> None:  # noqa: PLR0915
    """Run the wizard using Rich."""
    from rich import box
    from rich.console import Console
    from rich.panel import Panel
    from rich.prompt import Confirm
    from rich.table import Table

    console = Console()
    console.print()
    console.print(Panel.fit(
        "[bold cyan]Welcome to Tribunal[/bold cyan]\n"
        "[dim]First-run setup wizard[/dim]",
        border_style="cyan",
    ))
    console.print()

    # Step 1: Environment check
    console.print("[bold]Step 1/3: Environment Check[/bold]")
    checks = _check_env()
    table = Table(box=box.SIMPLE, show_header=False, padding=(0, 1))
    table.add_column("Status", width=4)
    table.add_column("Check", min_width=20)
    table.add_column("Detail")

    all_ok = True
    for label, ok, detail in checks:
        icon = "[green]✓[/green]" if ok else "[red]✗[/red]"
        table.add_row(icon, label, f"[dim]{detail}[/dim]")
        if not ok:
            all_ok = False
    console.print(table)

    if not all_ok:
        console.print("[yellow]⚠ Some prerequisites are missing. Installation may be incomplete.[/yellow]")
    console.print()

    # Step 3: Model selection
    console.print("[bold]Step 3/5: Default Model[/bold]")
    console.print("[dim]Which model would you like to use by default?[/dim]")
    console.print()
    console.print("  [cyan][1][/cyan] Claude Sonnet 4.5  [dim](recommended — balanced)[/dim]")
    console.print("  [cyan][2][/cyan] Claude Opus 4.5    [dim](most capable)[/dim]")
    console.print("  [cyan][3][/cyan] Claude Haiku 3.5   [dim](fastest)[/dim]")
    console.print("  [cyan][4][/cyan] Enter any model ID [dim](Claude or third-party passthrough)[/dim]")
    console.print("  [dim][Enter] to skip / use Claude Code default[/dim]")
    console.print()
    try:
        choice = console.input("  Choice [1-4/Enter]: ").strip()
        _model_map = {
            "1": "claude-sonnet-4-5",
            "2": "claude-opus-4-5",
            "3": "claude-haiku-3-5",
        }
        selected_model: str | None = None
        if choice in _model_map:
            selected_model = _model_map[choice]
        elif choice == "4":
            console.print("  [dim]Examples: claude-opus-4-5, minimax/MiniMax-Text-01, openai/gpt-4o[/dim]")
            custom = console.input("  Model ID: ").strip()
            if custom:
                selected_model = custom
        if selected_model:
            from launcher.config import set_model
            set_model(selected_model)
            console.print(f"[green]✓ Default model set to [cyan]{selected_model}[/cyan][/green]")
        else:
            console.print("[dim]Using Claude Code default model.[/dim]")
    except (EOFError, KeyboardInterrupt):
        console.print("[dim]Skipped model selection.[/dim]")
    console.print()

    # Step 4/5: Vault install offer (was step 2)
    console.print("[bold]Step 4/5: Vault Installation[/bold]")
    vault_dir = Path.home() / ".claude" / "tribunal"
    if vault_dir.exists():
        console.print(f"[green]✓ Vault already installed at {vault_dir}[/green]")
    else:
        console.print(f"[dim]Vault location: {vault_dir}[/dim]")
        try:
            install = Confirm.ask("Install Tribunal vault now?", default=True)
            if install:
                console.print("[dim]Run: tribunal install (or use your package manager)[/dim]")
        except (EOFError, KeyboardInterrupt):
            pass
    console.print()

    # Step 5/5: Offer /sync
    console.print("[bold]Step 5/5: Initial Sync[/bold]")
    console.print("[dim]You can run [cyan]/sync[/cyan] inside Claude Code to sync your vault.[/dim]")
    console.print()

    # Create ~/.tribunal to mark first run done
    SKILLFIELD_HOME.mkdir(parents=True, exist_ok=True)

    console.print("[green]✓ Setup complete! Run [bold]tribunal[/bold] to launch Claude Code.[/green]")
    console.print()


def _run_plain_wizard() -> None:
    """Run the wizard with plain print (no Rich available)."""
    print()
    print("=" * 60)
    print("Welcome to Tribunal - First Run Setup")
    print("=" * 60)

    checks = _check_env()
    print("\nEnvironment check:")
    for label, ok, detail in checks:
        status = "OK" if ok else "MISSING"
        print(f"  [{status}] {label}: {detail}")

    vault_dir = Path.home() / ".claude" / "tribunal"
    print(f"\nVault: {'installed at ' + str(vault_dir) if vault_dir.exists() else 'not installed'}")
    print("Tip: run /sync inside Claude Code to sync your vault.")
    print()

    SKILLFIELD_HOME.mkdir(parents=True, exist_ok=True)
    print("Setup complete! Run `tribunal` to launch Claude Code.")
    print()
