import { defineConfig } from '@rsbuild/core'
import { pluginReact } from '@rsbuild/plugin-react'
import { pluginLess } from '@rsbuild/plugin-less'
import { pluginSvgr } from '@rsbuild/plugin-svgr'
import type { EnvConfKey } from './src/config/env'
import { envConf } from './src/config/env'

const mode = process.env.MODE as EnvConfKey || 'dev'
const apiUrl = envConf[mode].apiUrl || ''
const proxyUrl = envConf[mode].proxyUrl || ''

// 处理 VITE_ 前缀的环境变量
const viteEnvVars: Record<string, string> = {}
Object.keys(process.env).forEach((key) => {
  if (key.startsWith('VITE_')) {
    viteEnvVars[`import.meta.env.${key}`] = JSON.stringify(process.env[key])
  }
})

// 根据 VITE_OUTPUT_OBJ 设置不同的 title 和 favicon
let htmlConfig = {
  title: '晓得. - 晓得解惑，让沟通更智能。',
  favicon: './src/assets/logo.png',
}

if (process.env.VITE_OUTPUT_OBJ === 'inner') {
  htmlConfig = {
    title: '建信消金AI智能问答',
    favicon: '',
  }
}

export default defineConfig({
  plugins: [
    pluginReact(),
    pluginLess(),
    pluginSvgr(),
  ],
  dev: {
    assetPrefix: '/sdream-ai',
  },
  html: htmlConfig,
  output: {
    target: 'web',
    assetPrefix: '/sdream-ai',
    distPath: {
      root: 'sdream-ai',
      image: 'assets',
      svg: 'assets',
      font: 'assets',
      media: 'assets',
    },
  },
  source: {
    define: {
      'import.meta.env.MODE': JSON.stringify(mode),
      ...viteEnvVars,
    },
  },
  server: {
    proxy: {
      [apiUrl]: {
        target: proxyUrl,
        pathRewrite: { [`^${apiUrl}`]: '' },
        changeOrigin: true,
      },
    },
  },
})
