import { defineConfig } from 'vite';
import { resolve } from 'node:path';

export default defineConfig({
  server: {
    port: 3000,
    open: true,
    // Proxy /api and /ws to the Node backend during dev.
    // BASE_URL is '/blocks/' in production but '/' in dev (see `base` below for prod builds).
    proxy: {
      // Frontend uses BASE_URL (/blocks/) prefix; strip it before forwarding to Node.
      '/blocks/api': {
        target: 'http://localhost:3001',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/blocks/, ''),
      },
      '/blocks/ws': {
        target: 'ws://localhost:3001',
        ws: true,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/blocks/, ''),
      },
    },
  },
  base: '/blocks/',
  build: {
    outDir: 'dist',
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html'),
        teacher: resolve(__dirname, 'teacher.html'),
      },
    },
  },
  optimizeDeps: {
    // esptool-js uses dynamic import() for chip targets (e.g. esp32s3.js); include them
    // so Vite pre-bundles them and the runtime fetch resolves.
    include: [
      'esptool-js',
      'esptool-js/lib/targets/esp32.js',
      'esptool-js/lib/targets/esp32c2.js',
      'esptool-js/lib/targets/esp32c3.js',
      'esptool-js/lib/targets/esp32c5.js',
      'esptool-js/lib/targets/esp32c6.js',
      'esptool-js/lib/targets/esp32c61.js',
      'esptool-js/lib/targets/esp32h2.js',
      'esptool-js/lib/targets/esp32p4.js',
      'esptool-js/lib/targets/esp32s2.js',
      'esptool-js/lib/targets/esp32s3.js',
      'esptool-js/lib/targets/esp8266.js',
    ],
  },
});
