#!/usr/bin/env python3
import argparse
import subprocess
import venv
from pathlib import Path

_DIR = Path(__file__).parent
_PROGRAM_DIR = _DIR.parent
_VENV_DIR = _PROGRAM_DIR / ".venv"

parser = argparse.ArgumentParser()
parser.add_argument("--dev", action="store_true", help="Install dev requirements")
parser.add_argument(
    "--train", action="store_true", help="Install training requirements"
)
parser.add_argument("--zh", action="store_true", help="Install Chinese requirements")
parser.add_argument("--ja", action="store_true", help="Install Japanese requirements")
parser.add_argument("--th", action="store_true", help="Install Thai requirements")
parser.add_argument(
    "--torch-cpu", action="store_true", help="Install CPU-only version of PyTorch"
)
parser.add_argument(
    "--constraint",
    help="pip constraints file with exact versions, such as .github/constraints.txt",
)
args = parser.parse_args()

constraint = []
if args.constraint:
    constraint = ["--constraint", str(Path(args.constraint).absolute())]

# Create virtual environment
builder = venv.EnvBuilder(with_pip=True)
context = builder.ensure_directories(_VENV_DIR)
builder.create(_VENV_DIR)

# Upgrade dependencies
pip = [context.env_exe, "-m", "pip"]
subprocess.check_call(pip + ["install", "--upgrade", "pip"] + constraint)
subprocess.check_call(
    pip + ["install", "--upgrade", "setuptools", "wheel"] + constraint
)

# PyTorch
if args.torch_cpu:
    subprocess.check_call(
        pip
        + [
            "install",
            "torch>=2,<3",
            "--extra-index-url",
            "https://download.pytorch.org/whl/cpu",
        ]
        + constraint
    )

# Install requirements
extras = []
if args.dev:
    extras.append("dev")

if args.train:
    extras.append("train")

if args.zh:
    extras.append("zh")

if args.ja:
    extras.append("ja")

if args.th:
    extras.append("th")

extras_str = ""
if extras:
    extras_str = "[" + ",".join(extras) + "]"

# The constraints also pin the build dependencies (cmake, scikit-build, ...)
# that pip installs to build Piper itself. The pip that came with the venv may
# predate --build-constraint, so this waits until pip has been upgraded.
build_constraint = []
if args.constraint:
    build_constraint = ["--build-constraint", str(Path(args.constraint).absolute())]

subprocess.check_call(
    pip
    + ["install", "-e", str(_PROGRAM_DIR) + extras_str]
    + constraint
    + build_constraint
)
