import { readFile, readdir } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
  buildPcre2Pack,
  parsePcre2BuildArguments,
} from "./pcre2-engine-pack.mjs";

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const options = parsePcre2BuildArguments(process.argv.slice(2));

if (options.mode === "help") {
  console.log(`Usage:
  node scripts/build-engines.mjs
  node scripts/build-engines.mjs --pcre2 --source-dir PATH --emcc PATH [--force]

The PCRE2 command is an explicit offline build gate. It verifies exact local
source and compiler identities, writes .engine-build/pcre2, and never
downloads or publishes an engine pack. Install the verified local pack with
npm run engines:pcre2:install.`);
  process.exit(0);
}

if (options.mode === "pcre2") {
  const result = await buildPcre2Pack(options, root);
  console.log(
    `Built and verified staged PCRE2 ${result.metadata.engineVersion} pack at ${result.output}.`,
  );
  console.log(
    "The verified pack remains in private staging until the explicit local install command is run.",
  );
  process.exit(0);
}

const packageJson = JSON.parse(
  await readFile(path.join(root, "package.json"), "utf8"),
);
const engineDirectory = path.join(root, "public", "engines");
const entries = (await readdir(engineDirectory)).sort();
const expectedEntries = [
  "README.md",
  "cpp",
  "dotnet",
  "go",
  "java",
  "pcre2",
  "perl",
  "php",
  "python",
  "ruby",
  "rust",
];

if (
  typeof packageJson.version !== "string" ||
  entries.length !== expectedEntries.length ||
  entries.some((entry, index) => entry !== expectedEntries[index])
) {
  throw new Error(
    "The production build requires every documented checked-in runtime pack.",
  );
}

console.log(
  `The checked-in ${expectedEntries
    .filter((entry) => entry !== "README.md")
    .join(
      ", ",
    )} runtime packs are present; no release-time download or engine compilation is needed.`,
);
