"""CLI command: engram init — zero-config quick start for new users."""

from __future__ import annotations

import os
from pathlib import Path

import typer
from rich.console import Console
from rich.panel import Panel

console = Console()

# Minimal config template — only the keys a new user needs
_CONFIG_TEMPLATE = """\
# Engram configuration — generated by `engram init`
# Edit this file to customise your setup.
# Full reference: https://github.com/yourusername/engram

episodic:
  provider: qdrant
  mode: embedded
  path: ~/.engram/qdrant

semantic:
  provider: sqlite
  path: ~/.engram/semantic.db

embedding:
  provider: gemini
  model: gemini-embedding-001
  api_key: ${GEMINI_API_KEY}

llm:
  provider: gemini
  model: gemini/gemini-2.5-flash
  api_key: ${GEMINI_API_KEY}

consolidation:
  enabled: true

serve:
  host: 127.0.0.1
  port: 8765
"""


def register(app: typer.Typer) -> None:
    """Register the `init` command on the main Typer app."""

    @app.command()
    def init(
        non_interactive: bool = typer.Option(
            False,
            "--non-interactive",
            help="Use all defaults without prompting (for CI/scripts).",
        ),
        force: bool = typer.Option(
            False,
            "--force",
            "-f",
            help="Overwrite existing config without asking.",
        ),
    ) -> None:
        """Zero-config quick start — creates ~/.engram/ and auto-configures IDEs."""
        _run_init(non_interactive=non_interactive, force=force)


def _run_init(non_interactive: bool = False, force: bool = False) -> None:
    """Core init logic (separated for testability)."""
    import sys

    # Auto-switch to non-interactive when stdin is not a TTY (piped/CI)
    if not sys.stdin.isatty() and not non_interactive:
        non_interactive = True

    console.print()
    console.print(
        Panel(
            "[bold cyan]Engram Init[/bold cyan]\n"
            "[dim]Zero-config quick start for AI persistent memory[/dim]",
            expand=False,
        )
    )
    console.print()

    engram_dir = Path.home() / ".engram"
    config_path = engram_dir / "config.yaml"

    # --- Step 1: Create ~/.engram directory ---
    engram_dir.mkdir(parents=True, exist_ok=True)
    console.print(f"  [green]✓[/green] Directory ready: [cyan]{engram_dir}[/cyan]")

    # --- Step 2: Write config.yaml ---
    if config_path.exists() and not force:
        if non_interactive:
            console.print(
                f"  [yellow]![/yellow] Config already exists at [cyan]{config_path}[/cyan] — skipping (use --force to overwrite)"
            )
        else:
            overwrite = _prompt_confirm(
                f"Config already exists at {config_path}. Overwrite?",
                default=False,
            )
            if not overwrite:
                console.print("  [dim]Keeping existing config.[/dim]")
                _finish(engram_dir, config_path, non_interactive)
                return

    config_path.write_text(_CONFIG_TEMPLATE)
    config_path.chmod(0o600)
    console.print(f"  [green]✓[/green] Config created: [cyan]{config_path}[/cyan]")

    # Create sub-directories referenced in config
    for sub in ("qdrant", "inbox"):
        (engram_dir / sub).mkdir(exist_ok=True)

    # --- Step 3: Ask for Gemini API key ---
    api_key = _collect_api_key(non_interactive)
    if api_key:
        _write_env_file(engram_dir, api_key)
        console.print(f"  [green]✓[/green] API key saved to [cyan]{engram_dir / '.env'}[/cyan]")
    else:
        console.print(
            "  [yellow]![/yellow] No API key set — add GEMINI_API_KEY to "
            f"[cyan]{engram_dir / '.env'}[/cyan] before running [cyan]engram serve[/cyan]"
        )

    _finish(engram_dir, config_path, non_interactive)


def _collect_api_key(non_interactive: bool) -> str:
    """Prompt user for Gemini API key. Returns empty string if skipped."""
    # Check existing env / .env file first
    existing_key = os.environ.get("GEMINI_API_KEY", "")
    env_file = Path.home() / ".engram" / ".env"
    if not existing_key and env_file.exists():
        for line in env_file.read_text().splitlines():
            line = line.strip()
            if line.startswith("GEMINI_API_KEY="):
                existing_key = line.split("=", 1)[1].strip().strip("'\"")
                break

    if existing_key:
        console.print("  [green]✓[/green] GEMINI_API_KEY already set")
        return existing_key

    if non_interactive:
        return ""

    console.print()
    console.print("  [dim]Get a free Gemini API key at:[/dim] [cyan]https://aistudio.google.com/apikey[/cyan]")
    try:
        key = typer.prompt(
            "  Enter your Gemini API key (press Enter to skip)",
            default="",
            hide_input=False,
        ).strip()
    except (KeyboardInterrupt, EOFError):
        key = ""

    return key


def _write_env_file(engram_dir: Path, api_key: str) -> None:
    """Write/update ~/.engram/.env with GEMINI_API_KEY."""
    env_path = engram_dir / ".env"
    lines: list[str] = []

    if env_path.exists():
        # Preserve existing lines, replace GEMINI_API_KEY if present
        for line in env_path.read_text().splitlines():
            if not line.strip().startswith("GEMINI_API_KEY="):
                lines.append(line)

    lines.append(f"GEMINI_API_KEY={api_key}")
    env_path.write_text("\n".join(lines) + "\n")
    env_path.chmod(0o600)


def _finish(engram_dir: Path, config_path: Path, non_interactive: bool) -> None:
    """Detect IDEs, configure MCP, print final summary."""
    # --- Step 4: Auto-detect IDEs and configure MCP ---
    ide_names: list[str] = []
    configured_count = 0

    try:
        from engram.setup.detector import scan_agents

        with console.status("[bold green]Scanning for AI agents...[/bold green]", spinner="dots"):
            pairs = scan_agents()

        installed_pairs = [(c, r) for c, r in pairs if r.installed]
        ide_names = [r.name for _, r in installed_pairs]

        if installed_pairs:
            console.print(f"  [green]✓[/green] Found: {', '.join(ide_names)}")
            # Auto-configure all detected IDEs
            for connector, _ in installed_pairs:
                try:
                    result = connector.configure(dry_run=False)
                    if result.success:
                        configured_count += 1
                except Exception as exc:  # noqa: BLE001
                    console.print(f"  [yellow]![/yellow] Could not configure {connector.display_name}: {exc}")
        else:
            console.print("  [dim]No AI agents detected — run [cyan]engram setup[/cyan] later to connect IDEs[/dim]")
    except Exception as exc:  # noqa: BLE001
        console.print(f"  [yellow]![/yellow] IDE detection skipped: {exc}")

    # --- Step 5: Print summary ---
    console.print()
    lines: list[str] = [
        f"  [green]✓[/green] Config ready at [cyan]{config_path}[/cyan]",
    ]

    if ide_names:
        lines.append(f"  [green]✓[/green] Found: {', '.join(ide_names)}")
    if configured_count:
        lines.append(f"  [green]✓[/green] MCP configured for {configured_count} IDE(s)")

    # --- Step 6: Auto-start (systemd on Linux, fallback to daemon) ---
    autostart_ok = _try_autostart()

    lines.append("")
    if autostart_ok:
        lines.append("  [green]engram auto-starts on boot (systemd)[/green]")
        lines.append("  Your AI agents now have persistent memory!")
    else:
        server_started = _try_start_server()
        if server_started:
            lines.append("  [green]engram server started in background[/green]")
            lines.append("  Your AI agents now have persistent memory!")
        else:
            lines.append("  [bold]Next step:[/bold] [cyan]engram start[/cyan]")
            lines.append("  Your AI agents will have persistent memory!")

    console.print(
        Panel(
            "\n".join(lines),
            title="[bold green]Ready![/bold green]",
            expand=False,
        )
    )
    console.print()


def _try_autostart() -> bool:
    """Try to install systemd autostart. Returns True on success (Linux only)."""
    import platform
    if platform.system() != "Linux":
        return False
    try:
        from engram.cli.autostart_cmd import _install_systemd
        return _install_systemd()
    except Exception as exc:
        console.print(f"  [yellow]![/yellow] Autostart setup failed: {exc}")
        return False


def _try_start_server() -> bool:
    """Try to start engram server in background. Returns True on success."""
    import subprocess
    import shutil

    engram_bin = shutil.which("engram")
    if not engram_bin:
        return False

    # Check if already running
    from engram.cli.daemon_cmd import _is_running
    running, _ = _is_running()
    if running:
        console.print("  [green]engram server already running[/green]")
        return True

    try:
        result = subprocess.run(
            [engram_bin, "start"],
            capture_output=True,
            text=True,
            timeout=10,
        )
        return result.returncode == 0
    except (OSError, subprocess.TimeoutExpired):
        return False


def _prompt_confirm(message: str, default: bool = True) -> bool:
    """Simple y/n prompt. Returns default on EOF/interrupt."""
    try:
        return typer.confirm(message, default=default)
    except (KeyboardInterrupt, EOFError):
        return default
