"""
`venvy pip install / uninstall` command.
Wraps pip and auto-updates requirements.txt.
"""

from __future__ import annotations

import sys
from pathlib import Path
from typing import List, Optional

import typer

from venvy.core.config import load_config, find_project_root
from venvy.core.pip_interceptor import run_pip_install, run_pip_uninstall
from venvy.core.venv_manager import find_venv, get_venv_python
from venvy.utils.console import console
from venvy.utils.platform_utils import get_active_venv


def _resolve_context():
    """Resolve venv, python executable, and req file for current project."""
    cwd = Path.cwd()
    
    # Find project root (may differ from cwd if we're in a subdir)
    root = find_project_root(cwd) or cwd
    config = load_config(root)
    req_file_name = config.requirements_file if config else "requirements.txt"
    req_file = root / req_file_name

    # Determine which Python to use
    active_venv = get_active_venv()
    if active_venv:
        python_exe = str(get_venv_python(Path(active_venv)))
    else:
        venv_path = find_venv(root)
        if venv_path:
            python_exe = str(get_venv_python(venv_path))
            console.print(
                f"[dim]Using venv at {venv_path}[/dim]"
            )
        else:
            console.print(
                "[yellow]⚠[/yellow]  No active virtual environment found. "
                "Using system Python.\n"
                "   Tip: run [bold]venvy create venv[/bold] first."
            )
            python_exe = sys.executable

    return python_exe, req_file


def pip_install_command(packages: List[str], upgrade: bool = False) -> None:
    """Install packages and update requirements.txt."""
    if not packages:
        console.print("[red]✗[/red] No packages specified.")
        raise typer.Exit(1)

    python_exe, req_file = _resolve_context()
    extra = ["-U"] if upgrade else []
    code = run_pip_install(packages, req_file, python_exe, extra)
    raise typer.Exit(code)


def pip_uninstall_command(packages: List[str], yes: bool = False) -> None:
    """Uninstall packages and remove from requirements.txt."""
    if not packages:
        console.print("[red]✗[/red] No packages specified.")
        raise typer.Exit(1)

    python_exe, req_file = _resolve_context()
    code = run_pip_uninstall(packages, req_file, python_exe, yes=yes)
    raise typer.Exit(code)
