'use strict';

import {promises as fs} from 'fs';
import path from 'path';
import {fileURLToPath} from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const SRC_DIR = path.join(__dirname, '..', 'src');
const DIST_DIR = path.join(__dirname, '..', 'dist');

async function ensureDir(dir) {
  await fs.mkdir(dir, { recursive: true });
}

// Remove only stale .js outputs, leaving anything else in dist (notably the
// CSS produced by the separate `build:css` step) untouched. Wiping the whole
// dist dir here would delete those CSS files whenever `build:js` runs alone.
async function cleanJsFiles(dir) {
  let entries;
  try {
    entries = await fs.readdir(dir, { withFileTypes: true });
  } catch (err) {
    if (err.code === 'ENOENT') return;
    throw err;
  }
  for (const entry of entries) {
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      await cleanJsFiles(full);
    } else if (entry.isFile() && entry.name.endsWith('.js')) {
      await fs.rm(full);
    }
  }
}

async function copyJsFiles(src, dest) {
  const entries = await fs.readdir(src, { withFileTypes: true });
  for (const entry of entries) {
    const srcPath = path.join(src, entry.name);
    const destPath = path.join(dest, entry.name);
    if (entry.isDirectory()) {
      await ensureDir(destPath);
      await copyJsFiles(srcPath, destPath);
    } else if (entry.isFile() && entry.name.endsWith('.js')) {
      await ensureDir(dest);
      await fs.copyFile(srcPath, destPath);
    }
  }
}

async function main() {
  await ensureDir(DIST_DIR);
  await cleanJsFiles(DIST_DIR);
  await copyJsFiles(SRC_DIR, DIST_DIR);
  // CSS build stays separate via npm run build:css
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
