#!/usr/bin/env node
import console from "node:console";
import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import process from "node:process";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";

const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const temporaryRoot = mkdtempSync(join(tmpdir(), "wrnexus-ui-reference-"));

function runGenerator() {
  const result = spawnSync(
    process.execPath,
    [join(temporaryRoot, "scripts", "generate-ui-component-reference.mjs")],
    {
      encoding: "utf8",
    },
  );
  if (result.status !== 0) {
    throw new Error(result.stderr || result.stdout || "UI component reference generator failed");
  }
}

try {
  mkdirSync(join(temporaryRoot, "scripts"), { recursive: true });
  mkdirSync(join(temporaryRoot, "packages", "ui"), { recursive: true });
  cpSync(
    join(root, "scripts", "generate-ui-component-reference.mjs"),
    join(temporaryRoot, "scripts", "generate-ui-component-reference.mjs"),
  );
  cpSync(
    join(root, "packages", "ui", "components"),
    join(temporaryRoot, "packages", "ui", "components"),
    {
      recursive: true,
    },
  );

  for (const name of ["component-catalog.json", "component-reference.json", "COMPONENTS.md"]) {
    cpSync(join(root, "packages", "ui", name), join(temporaryRoot, "packages", "ui", name));
  }

  // Bring the isolated copy to the generator's canonical content before
  // checking that a line-ending-only difference is preserved. The repository
  // artifact can legitimately be stale while this script is proving the
  // generator's newline behaviour.
  runGenerator();

  const jsonFiles = ["component-catalog.json", "component-reference.json"];
  const before = new Map();
  for (const name of jsonFiles) {
    const path = join(temporaryRoot, "packages", "ui", name);
    const crlf = readFileSync(path, "utf8").replace(/\r\n?/g, "\n").replace(/\n/g, "\r\n");
    writeFileSync(path, crlf);
    before.set(name, readFileSync(path));
  }

  runGenerator();

  for (const name of jsonFiles) {
    const path = join(temporaryRoot, "packages", "ui", name);
    if (!readFileSync(path).equals(before.get(name))) {
      throw new Error(`${name} was rewritten even though only line endings differed`);
    }
  }

  const referencePath = join(temporaryRoot, "packages", "ui", "component-reference.json");
  const canonicalCount = JSON.parse(readFileSync(referencePath, "utf8")).count;
  const stale = readFileSync(referencePath, "utf8").replace(
    `"count": ${canonicalCount}`,
    `"count": ${canonicalCount - 1}`,
  );
  writeFileSync(referencePath, stale);
  runGenerator();

  const restored = JSON.parse(readFileSync(referencePath, "utf8"));
  if (restored.count !== canonicalCount) {
    throw new Error("genuinely stale component reference content was not regenerated");
  }

  console.log("UI reference generation is line-ending stable and still repairs stale content.");
} finally {
  rmSync(temporaryRoot, { recursive: true, force: true });
}
