#!/usr/bin/env python3
import os
from pathlib import Path

import click
from tools import run

SDK_PROJECT_DIR = Path(os.environ["SDK_PROJECT_DIR"])
SITE_ROOT = Path(os.environ["SITE_ROOT"])


def install_pip_deps():
    run(
        [
            "python3.8",
            "-m",
            "pip",
            "install",
            "-r",
            f"{SITE_ROOT}/requirements.txt",
        ],
        check=True,
    )


def install_yarn_deps():
    for workdir in [
        SITE_ROOT / "src/web",
        SITE_ROOT / "tests",
    ]:
        args = ["yarn", "install", "--frozen-lockfile", "--non-interactive"]
        run(args, cwd=workdir, check=True)


def build_typescript():
    run(["webpack-cli"], cwd=f"{SITE_ROOT}/src/web", check=True)


@click.command()
@click.option("-t", "--tag", required=True)
@click.option("-c", "--config", required=True, type=click.Choice(["ci", "dev", "live"]))
@click.option("--push", is_flag=True)
@click.option("--no-cache", is_flag=True)
def main(tag, push, no_cache, config):
    install_yarn_deps()
    install_pip_deps()
    build_typescript()
    run(["django-admin", "collectstatic", "--no-input"], check=True)
    env = os.environ.copy()
    env.update({"TAG": tag})
    env.update({"CONFIG": config})
    if not push:
        env.update({"IMAGE_PREFIX": ""})
    run(
        ["docker-compose", "-f", f"{SDK_PROJECT_DIR}/build.yml", "build"]
        + (["--no-cache"] if no_cache else [])
        + ["base"],
        env=env,
    )
    run(
        ["docker-compose", "-f", f"{SDK_PROJECT_DIR}/build.yml", "build", "--parallel"]
        + (["--no-cache"] if no_cache else []),
        env=env,
    )
    if push:
        run(["login"], env=env)
        run(
            ["docker-compose", "-f", f"{SDK_PROJECT_DIR}/build.yml", "push"],
            env=env,
        )


if __name__ == "__main__":
    main()
