"""Config command for scry-run."""

import os
import shlex
import shutil
import subprocess
import sys

import click
from rich.console import Console

from scry_run.home import get_config_path
from scry_run.config import DEFAULT_CONFIG

console = Console()


def get_editor() -> list[str] | None:
    """Get the editor command to use, with sensible fallbacks.

    Priority:
    1. VISUAL env var
    2. EDITOR env var
    3. First available: nano, vim, vi, notepad (Windows)

    Returns:
        List of command parts (e.g., ["code", "--wait"]) or None
    """
    # Check env vars first (may contain args like "code --wait")
    if editor := os.environ.get("VISUAL"):
        return shlex.split(editor)
    if editor := os.environ.get("EDITOR"):
        return shlex.split(editor)

    # Sensible fallbacks
    fallbacks = ["nano", "vim", "vi"]
    if sys.platform == "win32":
        fallbacks = ["notepad", "code", "vim"]

    for editor in fallbacks:
        if shutil.which(editor):
            return [editor]

    return None


@click.command("config")
def config_cmd() -> None:
    """Open the scry-run config file in your editor.

    Creates a default config file if it doesn't exist.

    Editor selection (in order):
      1. $VISUAL
      2. $EDITOR
      3. nano, vim, vi (or notepad on Windows)
    """
    config_path = get_config_path()

    # Create config file with defaults if it doesn't exist
    if not config_path.exists():
        config_path.parent.mkdir(parents=True, exist_ok=True)
        config_path.write_text(DEFAULT_CONFIG)
        console.print(f"[green]Created config file:[/green] {config_path}")

    # Get editor
    editor_cmd = get_editor()
    if not editor_cmd:
        console.print("[red]Error:[/red] No editor found.")
        console.print("Set VISUAL or EDITOR environment variable, or install nano/vim.")
        raise SystemExit(1)

    editor_display = " ".join(editor_cmd)
    console.print(f"[dim]Opening {config_path} with {editor_display}...[/dim]")

    # Open editor (append file path to command)
    try:
        subprocess.run(editor_cmd + [str(config_path)], check=True)
    except subprocess.CalledProcessError as e:
        console.print(f"[red]Error:[/red] Editor exited with code {e.returncode}")
        raise SystemExit(e.returncode)
    except FileNotFoundError:
        console.print(f"[red]Error:[/red] Editor '{editor_cmd[0]}' not found")
        raise SystemExit(1)
