import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';

const outputRoot = new URL('../dist/esm/', import.meta.url);
const rootPath = outputRoot.pathname;

const files = (directory) => readdirSync(directory).flatMap((entry) => {
  const path = join(directory, entry);
  return statSync(path).isDirectory() ? files(path) : [path];
});

for (const path of files(rootPath).filter((candidate) => candidate.endsWith('.js'))) {
  const source = readFileSync(path, 'utf8');
  const withExtensions = source.replace(
    /((?:from\s+|import\s*)['"])(\.[^'"]+)(['"])/g,
    (_, prefix, specifier, suffix) => {
      if (specifier.endsWith('.js')) return `${prefix}${specifier}${suffix}`;
      const directoryTarget = resolve(dirname(path), specifier);
      const resolved = existsSync(directoryTarget) && statSync(directoryTarget).isDirectory()
        ? `${specifier}/index.js`
        : `${specifier}.js`;
      return `${prefix}${resolved}${suffix}`;
    },
  );
  writeFileSync(path, withExtensions);
}

writeFileSync(join(rootPath, 'package.json'), '{"type":"module"}\n');
