#!/usr/bin/env node
const fs = require("fs/promises");
const path = require("path");
const { spawnSync } = require("child_process");

const ROOT = process.cwd();
const HTML_DUMPS_DIR = path.join(ROOT, "html-dumps");
const EXPORTS_DIR = path.join(ROOT, "html-dumps-optimized");
const npxCmd = process.platform === "win32" ? "npx.cmd" : "npx";

async function removeExportsDir() {
  await fs.rm(EXPORTS_DIR, { recursive: true, force: true });
}

function runStep(cmd, args, options = {}) {
  const result = spawnSync(cmd, args, { stdio: "inherit", ...options });
  if (result.status !== 0) {
    throw new Error(
      `${cmd} ${args.join(" ")} failed with code ${result.status}`
    );
  }
}

async function processWorkflows() {
  await removeExportsDir();

  runStep(npxCmd, ["ts-node", "scripts/dom-export/exportHtmlDumps.ts"]);

  const entries = await fs.readdir(HTML_DUMPS_DIR, { withFileTypes: true });
  for (const entry of entries) {
    if (!entry.isDirectory()) continue;

    const exportWorkflowDir = path.join(EXPORTS_DIR, entry.name);
    try {
      await fs.access(exportWorkflowDir);
    } catch {
      continue;
    }

    runStep(npxCmd, [
      "ts-node",
      "scripts/dom-export/buildDomDiffs.ts",
      exportWorkflowDir,
    ]);
  }
}

processWorkflows().catch((err) => {
  console.error(err);
  process.exit(1);
});
