import { readdirSync, readFileSync, writeFileSync } from "node:fs";
import { basename, join } from "node:path";
import Handlebars from "handlebars";

const ROOT = join(import.meta.dirname, "..");
const TEMPLATES_DIR = join(ROOT, "src", "server", "templates");
const OUTPUT_FILE = join(ROOT, "src", "server", "templates.generated.js");

const hbsFiles = readdirSync(TEMPLATES_DIR)
  .filter((f) => f.endsWith(".hbs"))
  .sort();

const lines = [
  "// AUTO-GENERATED by scripts/precompile-templates.mjs. Do not edit.",
  'import Handlebars from "handlebars/runtime.js";',
  "",
];

for (const file of hbsFiles) {
  const name = basename(file, ".hbs");
  const source = readFileSync(join(TEMPLATES_DIR, file), "utf-8");
  const precompiled = Handlebars.precompile(source);
  lines.push(
    `/** @type {HandlebarsTemplateDelegate} */`,
    `export const ${name}Template = Handlebars.template(${precompiled});`,
  );
}

writeFileSync(OUTPUT_FILE, `${lines.join("\n")}\n`);
console.log(`Precompiled ${hbsFiles.length} template(s)`);
