import { readdirSync } from 'fs';
import { resolve } from 'path';
import { defineConfig } from 'vite';

// Auto-discover entry points
function getEntryPoints(): Record<string, string> {
  const entries: Record<string, string> = {};
  
  // Display modules (dp*.ts)
  const displayDir = resolve(__dirname, 'src/display');
  try {
    readdirSync(displayDir).forEach(file => {
      if (file.startsWith('dp') && file.endsWith('.ts')) {
        const name = file.replace('.ts', '');
        entries[name] = resolve(displayDir, file);
      }
    });
  } catch {
    console.warn('Display directory not found');
  }
  
  // Text modules (txt.ts only for the main loader)
  const textDir = resolve(__dirname, 'src/text');
  try {
    readdirSync(textDir).forEach(file => {
      if (file === 'txt.ts') {
        entries['txt'] = resolve(textDir, file);
      }
    });
  } catch {
    console.warn('Text directory not found');
  }
  
  // Test modules
  const testDir = resolve(__dirname, 'tests');
  try {
    readdirSync(testDir).forEach(file => {
      if (file.startsWith('test') && file.endsWith('.ts')) {
        const name = file.replace('.ts', '');
        entries[name] = resolve(testDir, file);
      }
    });
  } catch {
    console.warn('Tests directory not found');
  }
  
  return entries;
}

export default defineConfig({
  // Base path for deployment
  base: './',
  
  // Development server configuration
  server: {
    port: 3000,
    open: true,
    cors: true,
  },
  
  // Preview server (for production build testing)
  preview: {
    port: 4173,
    open: true,
  },
  
  // Path aliases
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
      '@display': resolve(__dirname, 'src/display'),
      '@text': resolve(__dirname, 'src/text'),
      '@yakus': resolve(__dirname, 'src/yakus'),
    },
  },
  
  // Build configuration
  build: {
    outDir: 'build',
    sourcemap: true,
    minify: 'terser',
    target: 'es2022',
    
    // Multiple entry points
    rollupOptions: {
      input: getEntryPoints(),
      output: {
        entryFileNames: '[name].js',
        chunkFileNames: 'chunks/[name]-[hash].js',
        assetFileNames: 'assets/[name]-[hash][extname]',
      },
    },
  },
  
  // CSS configuration
  css: {
    devSourcemap: true,
  },
});
