"""venvy create venv — interactive venv creation + pip wrapper injection."""
from __future__ import annotations
from pathlib import Path

import typer
from rich.prompt import Confirm, Prompt

from venvy.core import config as cfg_mod
from venvy.core.venv_manager import create, find, get_python
from venvy.core.injector import inject, is_injected
from venvy.utils.console import console


def run(
    venv_name: str = ".venv",
    req_file_name: str = "",
    ipykernel: bool = False,
    yes: bool = False,
) -> None:
    cwd = Path.cwd()
    existing = cfg_mod.load(cwd)

    if existing:
        console.print(
            f"[yellow]⚠[/yellow]  Already initialized.\n"
            f"   Venv: [bold]{existing.venv_name}[/bold] · "
            f"Requirements: [bold]{existing.req_file}[/bold]"
        )
        if not yes and not Confirm.ask("Re-initialize?", default=False):
            raise typer.Exit()

    console.print("\n[bold cyan]venvy[/bold cyan] — virtual environment setup\n" + "─" * 42)

    # Q1: ipykernel
    install_ipy = ipykernel if yes else Confirm.ask(
        "  [1/2] Install [bold]ipykernel[/bold] (Jupyter support)?", default=False
    )

    # Q2: requirements file
    chosen_req = (req_file_name or cfg_mod.DEFAULT_REQ) if yes else Prompt.ask(
        "  [2/2] Requirements file name", default=req_file_name or cfg_mod.DEFAULT_REQ
    )

    console.print()
    cfg = cfg_mod.Config(venv_name=venv_name, req_file=chosen_req, ipykernel=install_ipy)
    req_file = cwd / chosen_req
    venv_path = cwd / venv_name

    ok = create(venv_path, install_ipy, req_file if req_file.exists() else None)
    if not ok:
        # venv already existed — just inject if not done
        pass

    # Save config
    cfg_mod.save(cfg, cwd)

    # Inject pip wrapper into venv
    console.print("[cyan]→[/cyan] Installing pip tracker...")
    inject(venv_path)
    console.print("[green]✓[/green] pip tracker installed — [bold]pip install/uninstall will auto-update requirements.txt[/bold]")

    # Show activate instructions
    _show_activate(venv_path)


def _show_activate(venv: Path) -> None:
    import platform
    is_win = platform.system() == "Windows"
    console.print()
    if is_win:
        console.print(
            f"[bold green]✓ Ready![/bold green] Activate with:\n"
            f"  [cyan]{venv / 'Scripts' / 'activate.bat'}[/cyan]  (CMD)\n"
            f"  [cyan]{venv / 'Scripts' / 'Activate.ps1'}[/cyan]  (PowerShell)\n"
        )
    else:
        console.print(
            f"[bold green]✓ Ready![/bold green] Activate with:\n"
            f"  [cyan]source {venv / 'bin' / 'activate'}[/cyan]\n"
        )
    console.print("[dim]Once activated, pip install/uninstall automatically updates requirements.txt[/dim]")
