"""
Pip interceptor — wraps `pip install` and `pip uninstall` commands
to automatically update requirements.txt.

This works by:
1. The user calls `venvy pip install <pkg>` or `venvy pip uninstall <pkg>`
2. venvy runs the actual pip command inside the active venv
3. venvy then updates the requirements file

Alternatively, a shell function (printed by `venvy shell-init`) can
alias `pip` so every pip call goes through venvy automatically.
"""

from __future__ import annotations

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

from venvy.core.requirements_manager import (
    add_packages_to_requirements,
    remove_packages_from_requirements,
)
from venvy.utils.console import console


def run_pip_install(
    packages: List[str],
    req_file: Path,
    python_exe: str,
    extra_args: Optional[List[str]] = None,
) -> int:
    """Run pip install and update requirements.txt on success."""
    cmd = [python_exe, "-m", "pip", "install"] + packages + (extra_args or [])
    console.print(f"[cyan]→[/cyan] Running: {' '.join(cmd)}")
    result = subprocess.run(cmd, text=True)

    if result.returncode == 0:
        add_packages_to_requirements(packages, req_file, python_exe)
    else:
        console.print("[red]✗[/red] pip install failed — requirements not updated.")

    return result.returncode


def run_pip_uninstall(
    packages: List[str],
    req_file: Path,
    python_exe: str,
    yes: bool = False,
) -> int:
    """Run pip uninstall and remove from requirements.txt on success."""
    cmd = [python_exe, "-m", "pip", "uninstall"] + packages
    if yes:
        cmd.append("-y")
    console.print(f"[cyan]→[/cyan] Running: {' '.join(cmd)}")
    result = subprocess.run(cmd, text=True)

    if result.returncode == 0:
        remove_packages_from_requirements(packages, req_file)
    else:
        console.print("[red]✗[/red] pip uninstall failed — requirements not updated.")

    return result.returncode
