import os
import subprocess

from src.config import Configuration


def run_webpack():
    environment_vars = {
        **os.environ.copy(),
        "FLASK_DEBUG": "development" if Configuration().development_mode else "false",
        "NODE_ENV": "development" if Configuration().development_mode else "production",
        "KEMONO_SITE": Configuration().webserver["site"],
        "ICONS_PREPEND": Configuration().webserver["ui"]["files_url_prepend"]["icons_base_url"],
        "BANNERS_PREPEND": Configuration().webserver["ui"]["files_url_prepend"]["banners_base_url"],
        "THUMBNAILS_PREPEND": Configuration().webserver["ui"]["files_url_prepend"]["thumbnails_base_url"],
        "CREATORS_LOCATION": Configuration().webserver["api"]["creators_location"],
    }

    for k, v in environment_vars.items():
        os.environ[k] = v

    if not os.path.isdir("./client/node_modules"):
        subprocess.run(
            ["npm", "ci", "--also=dev", "--legacy-peer-deps"], check=True, cwd="client", env=environment_vars
        )
    os.chdir("client")
    os.execv("/usr/bin/sh", ["sh", "-c", "npm run dev"])
