import { build } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import { readdirSync, statSync, writeFileSync } from 'fs';

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

const appsDir = resolve(__dirname, 'src/apps');
const apps = readdirSync(appsDir).filter((file) => {
  const fullPath = resolve(appsDir, file);
  return statSync(fullPath).isDirectory();
});

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

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

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