"""Local Node tooling; manifests stay in Git, installation stays outside it."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess


REPO = Path(__file__).resolve().parents[1]
ENVIRONMENT = REPO.parent / "InvestmentEnvironment"
NODE = ENVIRONMENT / "node"


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("action", choices=("install", "npm", "build"))
    parser.add_argument("arguments", nargs=argparse.REMAINDER)
    args = parser.parse_args(argv)
    if args.action == "install":
        NODE.mkdir(parents=True, exist_ok=True)
        for name in ("package.json", "package-lock.json"):
            shutil.copy2(REPO / name, NODE / name)
        command = [shutil.which("npm.cmd" if os.name == "nt" else "npm"),
                   "ci", "--ignore-scripts", "--no-audit", "--no-fund",
                   "--cache", str(ENVIRONMENT / "npm-cache"), *args.arguments]
        return subprocess.run(command, cwd=NODE).returncode
    for name in ("package.json", "package-lock.json"):
        if not (NODE / name).is_file() or (NODE / name).read_bytes() != (REPO / name).read_bytes():
            parser.error("Run python tools/dev.py install to synchronize local Node dependencies")
    if args.action == "npm":
        arguments = args.arguments[1:] if args.arguments[:1] == ["--"] else args.arguments
        return subprocess.run([shutil.which("npm.cmd" if os.name == "nt" else "npm"),
                               *arguments], cwd=NODE).returncode
    build = argparse.ArgumentParser(prog="tools/dev.py build")
    build.add_argument("--output-dir", type=Path, default=ENVIRONMENT / "builds/css")
    output = build.parse_args(args.arguments).output_dir.resolve()
    if output == REPO or REPO in output.parents:
        build.error("Build output must stay outside the source checkout")
    output.mkdir(parents=True, exist_ok=True)
    env = os.environ.copy()
    env["NODE_PATH"] = str(NODE / "node_modules")
    cli = NODE / "node_modules/@tailwindcss/cli/dist/index.mjs"
    for name, source in (("website", "InvestmentWebsite/static/input.css"),
                         ("manager", "InvestmentManager/static/css/input.css")):
        result = subprocess.run([shutil.which("node"), str(cli), "--input", source,
                                 "--output", str(output / (name + ".css")), "--minify"],
                                cwd=REPO, env=env)
        if result.returncode:
            return result.returncode
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
