import { cpSync, existsSync, readdirSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vite';

const root = path.dirname(fileURLToPath(import.meta.url));
const excludedDirs = new Set(['.git', 'dist', 'node_modules']);

function collectHtmlInputs(dir) {
  const inputs = {};
  const entries = readdirSync(dir, { withFileTypes: true });

  for (const entry of entries) {
    const fullPath = path.join(dir, entry.name);

    if (entry.isDirectory()) {
      if (!excludedDirs.has(entry.name)) {
        Object.assign(inputs, collectHtmlInputs(fullPath));
      }
      continue;
    }

    if (entry.isFile() && entry.name.endsWith('.html')) {
      const relativePath = path.relative(root, fullPath);
      const inputName = relativePath
        .replace(/\.html$/, '')
        .replace(/[^a-zA-Z0-9_-]+/g, '_');

      inputs[inputName] = fullPath;
    }
  }

  return inputs;
}

function copyStaticAssets() {
  return {
    name: 'copy-static-assets',
    closeBundle() {
      const source = path.join(root, 'assets');
      const destination = path.join(root, 'dist', 'assets');

      if (existsSync(source)) {
        cpSync(source, destination, { recursive: true });
      }
    },
  };
}

export default defineConfig({
  plugins: [copyStaticAssets()],
  build: {
    rollupOptions: {
      input: collectHtmlInputs(root),
    },
  },
});
