"""CLI entry point for venv."""

import os
import subprocess
import sys
import venv
from pathlib import Path


VENV_NAME = ".venv"


def get_venv_path() -> Path:
    """Get the venv path in current directory."""
    return Path.cwd() / VENV_NAME


def is_venv_exists() -> bool:
    """Check if venv already exists."""
    venv_path = get_venv_path()
    
    # Check for activation scripts to confirm it's a valid venv
    if sys.platform == "win32":
        activate_script = venv_path / "Scripts" / "activate.bat"
    else:
        activate_script = venv_path / "bin" / "activate"
    
    return activate_script.exists()


def create_venv() -> bool:
    """Create a new venv. Returns True if successful."""
    venv_path = get_venv_path()
    
    print(f"Creating virtual environment at {venv_path}...")
    
    try:
        venv.create(venv_path, with_pip=True)
        print("Virtual environment created successfully!")
        return True
    except Exception as e:
        print(f"Error creating virtual environment: {e}", file=sys.stderr)
        return False


def get_activated_shell_env() -> dict:
    """Get environment variables for activated venv."""
    venv_path = get_venv_path()
    env = os.environ.copy()
    
    if sys.platform == "win32":
        scripts_dir = venv_path / "Scripts"
        env["PATH"] = str(scripts_dir) + os.pathsep + env.get("PATH", "")
    else:
        bin_dir = venv_path / "bin"
        env["PATH"] = str(bin_dir) + os.pathsep + env.get("PATH", "")
    
    env["VIRTUAL_ENV"] = str(venv_path)
    
    # Remove PYTHONHOME if set
    env.pop("PYTHONHOME", None)
    
    return env


def spawn_shell():
    """Spawn a new shell with venv activated."""
    venv_path = get_venv_path()
    env = get_activated_shell_env()
    
    print(f"Activating virtual environment: {venv_path}")
    print("Type 'exit' to deactivate and return to the original shell.\n")
    
    if sys.platform == "win32":
        # Detect the current shell
        shell = os.environ.get("COMSPEC", "cmd.exe")
        
        # Check if running in PowerShell
        if "powershell" in os.environ.get("PSModulePath", "").lower() or \
           os.environ.get("PSVersionTable"):
            # PowerShell
            subprocess.call(["powershell", "-NoExit", "-NoLogo"], env=env)
        else:
            # cmd.exe
            subprocess.call([shell], env=env)
    else:
        # Unix-like systems
        shell = os.environ.get("SHELL", "/bin/bash")
        subprocess.call([shell], env=env)


def main():
    """Main entry point."""
    import argparse
    
    parser = argparse.ArgumentParser(
        prog="venv",
        description="One-liner venv creation and activation tool. "
                    "Creates .venv if it doesn't exist, then activates it."
    )
    parser.add_argument(
        "--version", "-V",
        action="version",
        version=f"%(prog)s {__import__('venv_cli').__version__}"
    )
    parser.add_argument(
        "--create-only", "-c",
        action="store_true",
        help="Only create venv, don't activate"
    )
    parser.add_argument(
        "--path", "-p",
        action="store_true",
        help="Print the venv path and exit"
    )
    
    args = parser.parse_args()
    
    # Handle --path flag
    if args.path:
        print(get_venv_path())
        return 0
    
    # Check if venv exists, create if not
    if not is_venv_exists():
        if not create_venv():
            return 1
    else:
        print(f"Using existing virtual environment: {get_venv_path()}")
    
    # Activate (spawn shell) unless --create-only
    if not args.create_only:
        spawn_shell()
    
    return 0


if __name__ == "__main__":
    sys.exit(main())
