#!/usr/bin/env node
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
import { dirname, extname, join, resolve } from 'node:path';

const distDir = new URL('./dist/', import.meta.url).pathname.replace(/^\/([A-Z]:)/, '$1');
let fixed = 0;
let files = 0;

function processFile(filePath) {
  if (!filePath.endsWith('.js') && !filePath.endsWith('.d.ts')) return;
  files += 1;

  const fileDir = dirname(filePath);
  const content = readFileSync(filePath, 'utf8');
  let changed = false;

  const addExt = (match, prefix, specifier, suffix) => {
    const ext = extname(specifier);
    if (['.js', '.mjs', '.cjs', '.json', '.css'].includes(ext)) {
      return match;
    }
    const resolved = resolve(fileDir, specifier);
    const fileCandidates = [`${resolved}.js`, `${resolved}.mjs`, `${resolved}.cjs`, `${resolved}.d.ts`];
    if (fileCandidates.some((candidate) => existsSync(candidate))) {
      changed = true;
      return `${prefix}${specifier}.js${suffix}`;
    }
    if (existsSync(resolved) && statSync(resolved).isDirectory()) {
      changed = true;
      return `${prefix}${specifier}/index.js${suffix}`;
    }
    changed = true;
    return `${prefix}${specifier}.js${suffix}`;
  };

  const updated = content
    .replace(/(from\s+['"])(\.\.?\/[^'"]+)(['"])/g, addExt)
    .replace(/(import\(['"])(\.\.?\/[^'"]+)(['"]\))/g, addExt)
    .replace(/(import\s+['"])(\.\.?\/[^'"]+)(['"])/g, addExt);

  if (changed) {
    writeFileSync(filePath, updated);
    fixed += 1;
  }
}

function walk(dir) {
  for (const entry of readdirSync(dir)) {
    const full = join(dir, entry);
    if (statSync(full).isDirectory()) {
      walk(full);
    } else {
      processFile(full);
    }
  }
}

walk(distDir);
console.log(`Fixed ${fixed}/${files} files with .js extensions`);
