#!/usr/bin/env python3
import argparse
import subprocess
import venv
import os
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("--cxxflags", type=str, help="CXXFLAGS for compilation (default: -O1 -g0)")
parser.add_argument("--makeflags", type=str, help="MAKEFLAGS for compilation (default: -j1)")
args = parser.parse_args()

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

# Set environment variables
env = {}
if args.cxxflags:
    env["CXXFLAGS"] = args.cxxflags
if args.makeflags:
    env["MAKEFLAGS"] = args.makeflags

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

# Install requirements
subprocess.check_call(pip + ["install", "-e", str(_PROGRAM_DIR)])


# Install dev requirements
if args.dev:
    subprocess.check_call(
        pip + ["install", "-e", f"{_PROGRAM_DIR}[dev]"],
        env={**dict(os.environ), **env}
    )
