import { build } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'path';
import { readdirSync } from 'fs';

const appsDir = resolve(process.cwd(), 'src/apps');
const apps = readdirSync(appsDir, { withFileTypes: true })
  .filter(dirent => dirent.isDirectory())
  .map(dirent => dirent.name);

console.log(`Building ${apps.length} apps...`);

for (const app of apps) {
  console.log(`\nBuilding ${app}...`);
  
  await build({
    plugins: [react()],
    build: {
      outDir: `../../dist/apps/${app}`,
      emptyOutDir: true,
      rollupOptions: {
        input: resolve(appsDir, app, 'index.html'),
        output: {
          entryFileNames: 'app.js',
          assetFileNames: 'app.[ext]',
        },
      },
    },
    root: resolve(appsDir, app),
  });
}

console.log('\n✓ All apps built successfully!');
