import { defineConfig } from "vite";
import { resolve } from "path";
import fs from "fs";

function getInputs() {
  const inputs = {
    main: resolve(__dirname, "index.html"),
  };

  const entries = fs.readdirSync(__dirname, { withFileTypes: true });

  for (const entry of entries) {
    if (
      entry.isDirectory() &&
      entry.name !== "node_modules" &&
      entry.name !== "dist" &&
      !entry.name.startsWith(".")
    ) {
      const indexPath = resolve(__dirname, entry.name, "index.html");
      if (fs.existsSync(indexPath)) {
        inputs[entry.name] = indexPath;
      }
    }
  }

  return inputs;
}

export default defineConfig({
  plugins: [
    {
      name: "copy-assets",
      writeBundle() {
        function copyDir(srcDir, destDir, skipFile) {
          const entries = fs.readdirSync(srcDir, { withFileTypes: true });
          for (const entry of entries) {
            if (skipFile && entry.name === skipFile) continue;
            const src = resolve(srcDir, entry.name);
            const dest = resolve(destDir, entry.name);
            if (entry.isDirectory()) {
              fs.mkdirSync(dest, { recursive: true });
              copyDir(src, dest);
            } else {
              fs.mkdirSync(destDir, { recursive: true });
              fs.copyFileSync(src, dest);
            }
          }
        }

        const entries = fs.readdirSync(__dirname, { withFileTypes: true });
        for (const entry of entries) {
          if (
            entry.isDirectory() &&
            entry.name !== "node_modules" &&
            entry.name !== "dist" &&
            !entry.name.startsWith(".")
          ) {
            const dirPath = resolve(__dirname, entry.name);
            const indexPath = resolve(dirPath, "index.html");
            if (!fs.existsSync(indexPath)) continue;

            const destDir = resolve(__dirname, "dist", entry.name);
            copyDir(dirPath, destDir, "index.html");
          }
        }
      },
    },
  ],
  build: {
    rollupOptions: {
      input: getInputs(),
    },
  },
});
