/** Build the injectable position-edits render artifact from the canonical runtime. */

import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { buildSync } from "esbuild";
import { execFileSync } from "node:child_process";

const thisDir = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(thisDir, "..");
const entry = resolve(repoRoot, "stubs/position-edits-render-entry.ts");
const generatedDir = resolve(repoRoot, "src/generated");
const outPath = resolve(generatedDir, "position-edits-render-inline.ts");

const result = buildSync({
  entryPoints: [entry],
  bundle: true,
  write: false,
  platform: "browser",
  format: "iife",
  target: ["es2020"],
  minify: true,
  legalComments: "none",
});
const iife = result.outputFiles[0]?.text ?? "";
if (!iife) throw new Error("esbuild produced no output for position-edits-render-entry.ts");

mkdirSync(generatedDir, { recursive: true });
writeFileSync(
  outPath,
  [
    "// AUTO-GENERATED by scripts/build-position-edits-render.ts - do not edit",
    `const POSITION_EDITS_RENDER_IIFE: string = ${JSON.stringify(iife)};`,
    "",
    "/** Returns the pre-built position-edits render IIFE as a string constant. */",
    "export function getPositionEditsRenderScript(): string {",
    "  return POSITION_EDITS_RENDER_IIFE;",
    "}",
    "",
  ].join("\n"),
  "utf8",
);

try {
  execFileSync("bun", ["x", "oxfmt", outPath], { stdio: "ignore" });
} catch {
  // Formatting is best effort when the generator runs in a minimal environment.
}

console.log(
  JSON.stringify({ event: "position_edits_render_generated", outPath, bytes: iife.length }),
);
