"""Module to check for the Python version and environment."""

import sys
import os
import subprocess
import venv
import importlib.util


def version_check():
    """Check for the Python version."""
    if sys.version_info < (3, 12):
        sys.exit("Python version 3.12 or higher is required")


def pip_check():
    """Check for the pip installation."""
    if importlib.util.find_spec("pip") is None:
        sys.exit("Pip is not installed")


def venv_check():
    """Check for the virtual environment."""
    if hasattr(sys, "real_prefix") or (
        hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
    ):
        return

    venv_path = os.path.join(os.getcwd(), "cdrm-venv")
    venv_python = (
        os.path.join(venv_path, "bin", "python")
        if os.name != "nt"
        else os.path.join(venv_path, "Scripts", "python.exe")
    )

    if os.path.exists(venv_path):
        subprocess.call([venv_python] + sys.argv)
        sys.exit()

    answer = (
        input(
            "Program is not running from a virtual environment. To maintain "
            "compatibility, this program must be run from one.\n"
            "Would you like to create one? (Y/N): "
        )
        .strip()
        .upper()
    )
    if answer.startswith("Y"):
        print("Creating virtual environment...")
        venv.create(venv_path, with_pip=True)
        subprocess.call([venv_python] + sys.argv)
        sys.exit()
    else:
        print("Exiting program. Please run it from a virtual environment next time.")
        sys.exit(1)


def requirements_check():
    """Check for the requirements."""
    required_packages = [
        "pywidevine",
        "pyplayready",
        "flask",
        "flask_cors",
        "yaml",
        "mysql.connector",
    ]
    missing = []
    for pkg in required_packages:
        if "." in pkg:
            parent, _ = pkg.split(".", 1)
            if (
                importlib.util.find_spec(parent) is None
                or importlib.util.find_spec(pkg) is None
            ):
                missing.append(pkg)
        else:
            if importlib.util.find_spec(pkg) is None:
                missing.append(pkg)
    if not missing:
        return

    while True:
        user_input = (
            input(
                f"Missing packages: {', '.join(missing)}. Do you want to install them? (Y/N): "
            )
            .strip()
            .upper()
        )
        if user_input == "Y":
            print("Installing packages from requirements.txt...")
            subprocess.check_call(
                [sys.executable, "-m", "pip", "install", "-r", "requirements.txt"]
            )
            print("Installation complete.")
            break
        if user_input == "N":
            print("Dependencies required, please install them and run again.")
            sys.exit()
        else:
            print("Invalid input. Please enter 'Y' to install or 'N' to exit.")


def run_python_checks():
    """Run the Python checks."""
    if getattr(sys, "frozen", False):  # Check if running from PyInstaller
        return
    version_check()
    pip_check()
    venv_check()
    requirements_check()
