import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'node:url'

// 与主项目 frontend 的 /ai-web 代理一致；可通过 VITE_APP_BASE 覆盖
export default defineConfig(async ({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  const base = env.VITE_APP_BASE || '/ai-web/'

  const useHttps = process.argv.includes('--https') || env.VITE_HTTPS === 'true'
  let sslPlugin = []
  if (useHttps) {
    try {
      const basicSsl = (await import('@vitejs/plugin-basic-ssl')).default
      sslPlugin = [basicSsl()]
    } catch {
      /* basicSsl not installed, skip */
    }
  }

  return {
    base,
    plugins: [vue(), ...sslPlugin],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      port: 3001,
      host: '0.0.0.0',
      proxy: {
        '/api': {
          target: 'http://localhost:8080',
          changeOrigin: true
        },
        '/ws': {
          target: 'http://localhost:8080',
          ws: true
        }
      }
    }
  }
})
