"""Minimal Python Module"""
from pathlib import Path
from buildutils import *
import json
import re

Import('env', 'build', 'install')

localenv = env.Clone()

make_setup = build(localenv.SubstFile("setup.cfg", "setup.cfg.in"))

# copy scripts from the full Cython module
for script in ("ck2yaml", "cti2yaml", "ctml2yaml"):
    # The actual script
    s = build(env.Command(f"cantera/{script}.py",
                          f"#interfaces/cython/cantera/{script}.py",
                          Copy("$TARGET", "$SOURCE")))
    localenv.Depends(make_setup, s)

build_cmd = ("$python_cmd_esc -m pip wheel --no-build-isolation --no-deps "
             "--wheel-dir=build/python_minimal/dist build/python_minimal")
wheel_name = f"Cantera_minimal-{env['cantera_version']}-py3-none-any.whl"
mod = build(localenv.Command(f"#build/python_minimal/dist/{wheel_name}", "setup.cfg",
                             build_cmd))
env['python_module'] = mod

readme = localenv.Command("README.rst", "#README.rst", Copy("$TARGET", "$SOURCE"))
# The target of this command must match the file listed in setup.cfg.in
license = localenv.Command("LICENSE.txt", "#License.txt",
                           Copy("$TARGET", "$SOURCE"))
localenv.Depends(mod, [make_setup, readme, license, "setup.py", "pyproject.toml"])

install_cmd = ["$python_cmd_esc", "-m", "pip", "install"]
user_install = False
python_prefix = None

if localenv["python_prefix"] == "USER":
    # Install to the OS-dependent user site-packages directory
    install_cmd.append("--user")
    user_install = True
elif localenv["python_prefix"]:
    # A specific location for the Cantera python module has been given
    install_cmd.extend((f"--prefix={localenv.subst('$python_prefix')}",
                        "--no-warn-script-location"))
    python_prefix = localenv.subst("$python_prefix")
elif not env["default_prefix"]:
    install_cmd.append(f"--prefix={env['prefix']}")
    python_prefix = env["prefix"]

# Get information about installation paths
script = """\
import json
import site
vars = {
    "site_packages": site.getsitepackages(),
    "user_site_packages": site.getusersitepackages(),
}
print(json.dumps(vars))
"""
info = json.loads(get_command_output(localenv["python_cmd"], "-c", script))
site_packages = info["site_packages"]
user_site_packages = info["user_site_packages"]

# Check for existing Python module installation. Allow pip to remove an existing
# installation only if we're installing to the same location. Also disable
# uninstallation if we're installing to a staging directory.
if env["stage_dir"]:
    install_cmd.append("--ignore-installed")
else:
    info = get_command_output(
        localenv["python_cmd"], "-m", "pip", "show", "cantera-minimal",
        ignore_errors=True
    )

    if user_install:
        test_prefix = Path(user_site_packages).parents[2]
    elif python_prefix is None:
        test_prefix = Path(site_packages[0]).parents[2]
    else:
        test_prefix = Path(python_prefix)

    match = re.search(r"Location: (.*)\n", info, re.MULTILINE)
    existing_prefix = Path(match.group(1)).parents[2] if match else None
    if existing_prefix and existing_prefix != test_prefix:
        install_cmd.append("--ignore-installed")

if env["stage_dir"]:
    # Get the absolute path to the stage directory. If the stage directory is a relative
    # path, consider it to be relative to the root of the Cantera source directory.
    stage_dir = Path(env["stage_dir"])
    if not stage_dir.is_absolute():
        stage_dir = Path(Dir("#").abspath) / stage_dir

    install_cmd.extend((f"--root={stage_dir.resolve()}", "--no-warn-script-location"))

install_cmd.extend(("--no-build-isolation", "--no-deps", "-v", "--force-reinstall",
                    "build/python_minimal"))
mod_inst = install(localenv.Command, 'dummy', mod, " ".join(install_cmd))
env['install_python_action'] = mod_inst
install_locs = get_pip_install_location(localenv["python_cmd"], user_install,
                                        python_prefix)
env["ct_pyscriptdir"] = install_locs["scripts"]
