import fs from "node:fs";

const esmSource = fs.readFileSync("./json-with-bigint.js", "utf-8");
const prefix = `// This file is auto-generated. Do not edit this file directly. 
// Instead edit the json-with-bigint.js and regenerate this file using:
// npm run build:cjs

"use strict";

`;

const exportedNames = new Set();

// Find export { name1, name2 }
const namedExportsMatch = esmSource.match(/export\s*\{([^}]+?)\}/s);
if (namedExportsMatch) {
  namedExportsMatch[1]
    .split(",")
    .map((name) => name.trim())
    .filter(Boolean)
    .forEach((name) => exportedNames.add(name));
}

// Find export foo;
const singleExports = esmSource.match(/export\s+(\w+)\s*;/g);
if (singleExports) {
  singleExports.forEach((match) => {
    const name = match.match(/export\s+(\w+)/)?.[1];
    if (name) exportedNames.add(name);
  });
}

// Find export default foo;
const defaultExport = esmSource.match(/export\s+default\s+(\w+)/);
if (defaultExport) {
  exportedNames.add(defaultExport[1]);
}

let cjsSource = esmSource
  // Remove export { ... }
  .replace(/^\s*export\s*\{[^}]+\}\s*;?\s*$/gm, "")
  // Remove export name;
  .replace(/^\s*export\s+\w+\s*;?\s*$/gm, "")
  // Remove export default name;
  .replace(/^\s*export\s+default\s+\w+\s*;?\s*$/gm, "")
  // Remove export default (...)
  .replace(/^\s*export\s+default\s+.+?$/gm, "")
  .trim();

const exportsList = Array.from(exportedNames).join(", ");

const moduleExports =
  exportedNames.size > 0 ? `module.exports = { ${exportsList} };` : "";

cjsSource = prefix + cjsSource + `\n\n${moduleExports}\n`;

fs.writeFileSync("./json-with-bigint.cjs", cjsSource, "utf8");
console.log("✅ CJS generated: module.exports = { " + exportsList + " }");
