import { defineConfig, loadEnv } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import { LLM_PROXY_TARGET } from './config/llm.js'

const llmTarget = String(LLM_PROXY_TARGET || '').replace(/\/$/, '')

/** 与 manifest.json h5.router.base 一致：生产 /bqH5/，开发 / */
function resolvePublicPath(mode, env) {
  if (mode !== 'production') {
    return '/'
  }
  const raw = String(env.VITE_APP_PUBLIC_PATH || 'bqH5').trim()
  if (!raw || raw === '/') {
    return '/'
  }
  return `/${raw.replace(/^\/+|\/+$/g, '')}/`
}

/**
 * uni-app Vue3 H5 开发代理
 * - /dev-api → 若依后端（.env.development 的 VITE_APP_API_HOST）
 * - /llm-dev-proxy → 大模型网关
 */
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  const base = resolvePublicPath(mode, env)
  const devApiTarget = String(env.VITE_APP_API_HOST || 'http://192.168.1.6:8010').replace(/\/$/, '')
  const devApiPrefix = String(env.VITE_APP_BASE_API || '/dev-api')

  return {
    base,
    plugins: [uni()],
    build: {
      // iOS Safari 对 modulepreload 更敏感，预加载未使用的 chunk 易拖慢首屏
      modulePreload: false
    },
    server: {
      proxy: {
        [devApiPrefix]: {
          target: devApiTarget,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^${devApiPrefix}`), '')
        },
        '/llm-dev-proxy': {
          target: llmTarget,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/llm-dev-proxy/, '')
        }
      }
    }
  }
})
