import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'

// Bundle analyzer: only active when ANALYZE=true is set in the environment.
// Usage: ANALYZE=true npm run build
// Output: stats.html in the project root (committed to .planning/perf/ manually).
function conditionalAnalyzer(env) {
  if (env.ANALYZE !== 'true') return null
  // Dynamic import so the package is never executed during normal builds.
  return import('rollup-plugin-visualizer').then(({ visualizer }) =>
    visualizer({ open: false, filename: 'stats.html', gzipSize: true })
  )
}

export default defineConfig(async ({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  const analyzerPlugin = await conditionalAnalyzer(env)

  return {
    plugins: [vue(), ...(analyzerPlugin ? [analyzerPlugin] : [])],
    build: {
      // top-level await in main.js requires esnext target
      target: 'esnext',
    },
    server: {
      host: '0.0.0.0',
      port: 5173,
      proxy: {
        '/api': {
          target: 'http://backend:8000',
          changeOrigin: true,
        },
      },
    },
  }
})
