"""
venvy.commands.create
~~~~~~~~~~~~~~~~~~~~~
Implements: venvy create venv
"""

from __future__ import annotations

from pathlib import Path
from typing import Optional

import typer
from rich.console import Console
from rich.prompt import Confirm, Prompt

from venvy.core.config import VenvyConfig
from venvy.core.pip_wrapper import install_pip_wrapper
from venvy.core.venv import VenvManager

console = Console()


def cmd_create_venv(
    name: Optional[str] = None,
    req_file: Optional[str] = None,
    ipykernel: Optional[bool] = None,
    python: Optional[str] = None,
) -> None:
    """Interactive command to create a new virtual environment."""
    cwd = Path.cwd()

    console.print("\n[bold cyan]venvy[/bold cyan] — Virtual Environment Setup\n")

    # --- Ask questions if not provided via flags ---
    if ipykernel is None:
        ipykernel = Confirm.ask(
            "[bold]Install ipykernel?[/bold] (for Jupyter notebook support)",
            default=False,
        )

    if req_file is None:
        req_file = Prompt.ask(
            "[bold]Requirements file name[/bold]",
            default="requirements.txt",
        )

    venv_name = name or ".venv"

    # --- Check if venv already exists ---
    venv_mgr = VenvManager(project_root=cwd, venv_name=venv_name)
    if venv_mgr.exists:
        overwrite = Confirm.ask(
            f"[yellow]Virtual environment '{venv_name}' already exists. Recreate?[/yellow]",
            default=False,
        )
        if not overwrite:
            console.print("[dim]Skipping venv creation.[/dim]")
        else:
            import shutil
            shutil.rmtree(venv_mgr.venv_path)
            _create(venv_mgr, python)
    else:
        _create(venv_mgr, python)

    # --- Save config ---
    config = VenvyConfig(
        venv_name=venv_name,
        requirements_file=req_file,
        ipykernel=ipykernel,
        python=python,
    )
    config_path = config.save(cwd)
    console.print(f"[dim]Saved config → {config_path.name}[/dim]")

    # --- Install ipykernel if requested ---
    if ipykernel and venv_mgr.exists:
        console.print("[cyan]Installing ipykernel...[/cyan]")
        ok, msg = venv_mgr.install_ipykernel(project_name=cwd.name)
        if ok:
            console.print(f"[green]✓[/green] {msg}")
        else:
            console.print(f"[yellow]⚠[/yellow] {msg}")

    # --- Install pip wrapper ---
    if venv_mgr.exists:
        console.print("[cyan]Installing venvy pip hook...[/cyan]")
        try:
            install_pip_wrapper(venv_mgr.venv_path)
            console.print(
                f"[green]✓[/green] pip hook installed — "
                f"'{req_file}' will be auto-updated on install/uninstall"
            )
        except Exception as e:
            console.print(f"[yellow]⚠ Could not install pip hook:[/yellow] {e}")

    # --- Final instructions ---
    console.print()
    console.print("[bold green]✓ Setup complete![/bold green]")
    console.print()
    console.print("To activate your virtual environment, run:")
    console.print(f"  [bold cyan]venvy +[/bold cyan]")
    console.print()
    console.print("  [dim](First run `venvy init-shell` once to enable shell integration)[/dim]")
    console.print()


def _create(venv_mgr: VenvManager, python: Optional[str]) -> None:
    console.print(f"[cyan]Creating virtual environment at '{venv_mgr.venv_name}'...[/cyan]")
    ok, msg = venv_mgr.create(python_executable=python)
    if ok:
        console.print(f"[green]✓[/green] {msg}")
    else:
        console.print(f"[red]✗[/red] {msg}")
        raise typer.Exit(1)
