import os
import pip
import sys
import sysconfig
import locale
import traceback
import subprocess

if not hasattr(pip, "main"):
    import pip._internal as pip

os.environ.pop("PIP_REQ_TRACKER", None)

MODULES = [
    # set modules, whitch can install
    "h5py",
    "numpy",
    "matplotlib",
]
UPGRADE_MODULES: bool = True
UPGRADE_PIP: bool = False
# if not started from python console
RUN_IN_PROCESS: bool = "pixet" not in dir(sys.modules["__main__"])

PYTHON_VERSION = f"{sys.version_info.major}.{sys.version_info.minor}"
LOCALE_ENCODING = locale.getpreferredencoding()


def runProcess(*cmd, stdout=sys.stdout):
    print(cmd)
    with subprocess.Popen(cmd, stdout=stdout, stderr=subprocess.STDOUT) as proc:
        while True:
            retcode = proc.poll()
            if stdout is not sys.stdout:
                line = proc.stdout.readline()
                print(line.strip().decode(LOCALE_ENCODING, errors="ignore"))

            if retcode is not None:
                break


# started from pyscripting
target = sysconfig.get_paths()["purelib"]
cmd = [
    "install",
    f"--target={target}",
    "--no-cache",
    "--disable-pip-version-check",
]

if UPGRADE_MODULES:
    cmd.append("--upgrade")

if UPGRADE_PIP and RUN_IN_PROCESS:
    runProcess(sys.executable, "-m", "pip", "install", "--upgrade", "pip")

if RUN_IN_PROCESS:
    runProcess(sys.executable, "-m", "pip", *cmd, *MODULES)
else:
    os.environ.pop("PIP_REQ_TRACKER", None)

    pip.main([*cmd, *MODULES])
