"""
venvy CLI — minimal, focused on requirements tracking.

Commands:
  venvy create venv     Create venv + install pip tracker
  venvy inject [path]   Add pip tracker to existing venv
  venvy status          Show project status
  venvy list            List requirements
  venvy sync            Install all from requirements.txt
"""
from __future__ import annotations
from typing import List, Optional

import typer
from rich.panel import Panel
from venvy import __version__
from venvy.utils.console import console

app = typer.Typer(
    name="venvy",
    help="Auto-tracks pip installs/uninstalls in requirements.txt.",
    add_completion=True,
    rich_markup_mode="rich",
    no_args_is_help=False,
)
create_app = typer.Typer(help="Create resources.")
app.add_typer(create_app, name="create")


def _version_cb(v: bool) -> None:
    if v:
        console.print(f"[bold cyan]venvy[/bold cyan] v{__version__}")
        raise typer.Exit()


@app.callback(invoke_without_command=True)
def main(
    ctx: typer.Context,
    version: Optional[bool] = typer.Option(None, "--version", "-v", callback=_version_cb, is_eager=True),
) -> None:
    if ctx.invoked_subcommand is None:
        console.print(Panel.fit(
            f"[bold cyan]venvy[/bold cyan] v{__version__}\n"
            "[dim]Auto-tracks pip installs in requirements.txt[/dim]\n\n"
            "[bold]Commands:[/bold]\n"
            "  [cyan]venvy create venv[/cyan]    — create venv + enable auto-tracking\n"
            "  [cyan]venvy inject[/cyan]         — add tracking to existing venv\n"
            "  [cyan]venvy status[/cyan]         — show venv & requirements info\n"
            "  [cyan]venvy list[/cyan]           — list tracked packages\n"
            "  [cyan]venvy sync[/cyan]           — install all from requirements.txt\n\n"
            "[dim]Once set up, just use pip normally:[/dim]\n"
            "  pip install flask      [dim]→ added to requirements.txt ✓[/dim]\n"
            "  pip uninstall flask    [dim]→ removed from requirements.txt ✓[/dim]",
            title="[bold]Welcome to venvy[/bold]",
            border_style="cyan",
        ))


# ── create venv ──────────────────────────────────────────────────────
@create_app.command("venv")
def create_venv(
    venv_name: str = typer.Option(".venv", "--name", "-n"),
    req_file: str = typer.Option("", "--requirements", "-r"),
    ipykernel: bool = typer.Option(False, "--ipykernel/--no-ipykernel"),
    yes: bool = typer.Option(False, "--yes", "-y", help="Use defaults, skip prompts."),
) -> None:
    """Create a virtual environment and enable pip auto-tracking."""
    from venvy.commands.create_cmd import run
    run(venv_name=venv_name, req_file_name=req_file, ipykernel=ipykernel, yes=yes)


# ── inject ───────────────────────────────────────────────────────────
@app.command()
def inject(
    venv_path: str = typer.Argument("", help="Path to venv (auto-detected if omitted)."),
) -> None:
    """
    Add pip auto-tracking to an existing virtual environment.

    Use this when you created a venv manually (python -m venv .venv)
    instead of using `venvy create venv`.

    Example:
      venvy inject          # auto-detects .venv
      venvy inject myenv    # specific venv
    """
    from venvy.commands.inject_cmd import run
    run(venv_path)


# ── status ───────────────────────────────────────────────────────────
@app.command()
def status() -> None:
    """Show current venv, tracker status, and requirements."""
    from venvy.commands.status_cmd import run
    run()


# ── list ─────────────────────────────────────────────────────────────
@app.command("list")
def list_pkgs() -> None:
    """List all packages in requirements.txt."""
    import os
    from pathlib import Path
    from venvy.core import config as cfg_mod
    from venvy.core.requirements import parse

    cwd = Path.cwd()
    root = cfg_mod.find_root(cwd)
    cfg = cfg_mod.load(root) if root else None
    req_name = cfg.req_file if cfg else "requirements.txt"
    req_file = (root or cwd) / req_name
    pkgs = parse(req_file)
    if not pkgs:
        console.print(f"[dim]No packages in {req_name}[/dim]")
        return
    console.print(f"\n[bold]{req_name}[/bold] — {len(pkgs)} packages:")
    for entry in sorted(pkgs.values()):
        console.print(f"  [cyan]•[/cyan] {entry}")
    console.print()


# ── sync ─────────────────────────────────────────────────────────────
@app.command()
def sync() -> None:
    """Install all packages listed in requirements.txt into the active venv."""
    import os, sys, subprocess
    from pathlib import Path
    from venvy.core import config as cfg_mod
    from venvy.core.venv_manager import find, get_python

    cwd = Path.cwd()
    root = cfg_mod.find_root(cwd)
    cfg = cfg_mod.load(root) if root else None
    req_name = cfg.req_file if cfg else "requirements.txt"
    req_file = (root or cwd) / req_name

    if not req_file.exists():
        console.print(f"[red]✗[/red] {req_name} not found.")
        raise typer.Exit(1)

    active = os.environ.get("VIRTUAL_ENV")
    if active:
        python = str(get_python(Path(active)))
    else:
        venv = find(root or cwd)
        python = str(get_python(venv)) if venv else sys.executable

    console.print(f"[cyan]→[/cyan] Installing from [bold]{req_name}[/bold]...")
    r = subprocess.run([python, "-m", "pip", "install", "-r", str(req_file)])
    if r.returncode == 0:
        console.print("[green]✓[/green] Done.")
    else:
        raise typer.Exit(r.returncode)
