import { defineConfig } from 'vite';
import { readFileSync, writeFileSync } from 'fs';

function generateSW() {
  return {
    name: 'generate-sw',
    apply: 'build',
    closeBundle() {
      const staticAssets = [
        '/',
        '/manifest.json',
        '/icons/icon-192.png',
        '/icons/icon-512.png',
      ];

      try {
        const manifest = JSON.parse(readFileSync('dist/.vite/manifest.json', 'utf-8'));
        for (const entry of Object.values(manifest)) {
          staticAssets.push('/' + entry.file);
          if (entry.css) entry.css.forEach(f => staticAssets.push('/' + f));
        }
      } catch {
      }

      const template = readFileSync('sw.js', 'utf-8');
      const out = template.replace('__PRECACHE_URLS__', JSON.stringify(staticAssets, null, 4));
      writeFileSync('dist/sw.js', out);

      console.log('[generate-sw] wrote dist/sw.js with', staticAssets.length, 'precache URLs');
    },
  };
}

export default defineConfig({
  root: '.',
  base: '/tower/',
  build: {
    outDir: 'dist',
    assetsDir: 'assets',
    target: 'esnext',
    manifest: true,
  },
  plugins: [generateSW()],
  server: {
    host: true,
    proxy: {
      '/api': 'http://localhost:8080',
    },
  },
  optimizeDeps: {
    // @xenova/transformers uses dynamic imports + WASM; exclude from pre-bundling
    exclude: ['@xenova/transformers'],
  },
  worker: {
    // Bundle Web Workers as ES modules so they can use import() and ESM packages
    format: 'es',
  },
});
