import { existsSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

const __dirname = dirname(fileURLToPath(import.meta.url))
const oxideVendored = [
  join(__dirname, 'vendor', 'tailwindcss-oxide.linux-x64-gnu.node'),
  join(__dirname, 'vendor', 'tailwindcss-oxide.linux-x64-musl.node'),
]
for (const p of oxideVendored) {
  if (existsSync(p)) {
    process.env.NAPI_RS_NATIVE_LIBRARY_PATH = p
    break
  }
}

export default defineConfig(async () => {
  const { default: tailwindcss } = await import('@tailwindcss/vite')
  return {
    plugins: [react(), tailwindcss()],
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      chunkSizeWarningLimit: 750,
      rollupOptions: {
        output: {
          // Stabilní vendor chunky: react jádro, grafové knihovny zvlášť (cache + menší initial load).
          manualChunks: {
            'vendor-react': ['react', 'react-dom', 'react-router-dom'],
            'vendor-recharts': ['recharts'],
            'vendor-nivo': ['@nivo/core', '@nivo/sankey'],
            'vendor-chartjs': ['chart.js'],
          },
        },
      },
    },
    server: {
      proxy: {
        '/ws': {
          target: 'http://localhost:8000',
          changeOrigin: true,
          ws: true,
        },
        '/api': {
          target: 'http://localhost:8000',
          changeOrigin: true,
        },
        '/rest': {
          target: 'http://localhost:3000',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/rest/, ''),
        },
      },
    },
  }
})
