import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'

// Port assignment is centralised via env vars to avoid conflicts with
// other local services (Docker, geo_backend, pms-*, etc.).
//   BACKEND_PORT   — AgentKit server port (default 18001, very-uncommon port)
//   VITE_DEV_PORT  — Vite dev server port (default 15173, avoids 5173 conflicts)
//   VITE_HMR_PORT  — Vite HMR websocket port (default 15174)
const host = process.env.TAURI_DEV_HOST
const backendPort = process.env.BACKEND_PORT || '18001'
const vitePort = parseInt(process.env.VITE_DEV_PORT || '15173', 10)
const hmrPort = parseInt(process.env.VITE_HMR_PORT || '15174', 10)

export default defineConfig({
  plugins: [
    vue(),
    Components({
      resolvers: [
        AntDesignVueResolver({
          importStyle: false, // css in js mode for ant-design-vue 4.x
        }),
      ],
    }),
  ],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
    },
  },
  build: {
    outDir: '../static',
    emptyOutDir: true,
  },
  // Tauri dev server configuration
  clearScreen: false,
  server: {
    port: vitePort,
    strictPort: true,
    // 2026-07-01: bind to all interfaces so Tauri's Rust-side reachability
    // check (which may use IPv4 127.0.0.1) can connect. Previously `host || false`
    // made Vite bind only IPv6 [::1] on macOS, causing Tauri to fall back to
    // frontendDist (static/) and serve a stale build — Cmd+R could not pick
    // up HMR changes. `true` listens on 0.0.0.0 (IPv4) + [::] (IPv6).
    host: host || true,
    hmr: host ? { protocol: 'ws', host, port: hmrPort } : undefined,
    watch: {
      ignored: ['**/src-tauri/**'],
    },
    proxy: {
      '/api': {
        target: `http://localhost:${backendPort}`,
        changeOrigin: true,
        ws: true,
      },
    },
  },
  envPrefix: ['VITE_', 'TAURI_', 'BACKEND_'],
})
