import * as esbuild from "esbuild";
import fs from "node:fs/promises";
import path from "node:path";

const filesToCopy = [
  "node_modules/htmx.org/dist/htmx.min.js",
  "node_modules/htmx-ext-preload/dist/preload.min.js",
  "node_modules/htmx-ext-head-support/dist/head-support.min.js",
];

const filesToMinifyRoot = "web/src/js";

const outputRoot = "web/static/js";

async function minifyFiles() {
  try {
    const files = (await fs.readdir(filesToMinifyRoot))
      .filter((p) => p.endsWith(".js"))
      .map((p) => {
        return {
          src: path.join(filesToMinifyRoot, p),
          dest: path.join(outputRoot, p.substring(0, p.length - 3) + ".min.js"),
        };
      });

    for (const file of files) {
      await esbuild.build({
        entryPoints: [file.src],
        bundle: false,
        minify: true,
        outfile: file.dest,
      });
      console.log(`Minified ${file.src} to ${file.dest}`);
    }
  } catch (err) {
    console.error("could not minify files", err);
  }
}

async function coppyFromNodemodules() {
  try {
    const fileMap = filesToCopy.map((file) => {
      return {
        src: file,
        dest: path.join(outputRoot, path.basename(file)),
      };
    });

    for (const file of fileMap) {
      await fs.copyFile(file.src, file.dest);
      console.log(`Copied ${path.basename(file.dest)}`);
    }
  } catch (err) {
    console.error("JS build failed:", err);
    process.exit(2);
  }
}

async function build() {
  console.log("Starting JS build...");

  await minifyFiles();
  await coppyFromNodemodules();

  console.log("JS build complete!");
}

build();

