import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { defineConfig, loadEnv } from 'vite'
import { analyzer } from 'vite-bundle-analyzer'
import { versionInfoPlugin } from '@tianyio/quality-helper/version-plugin'

const rootPath = resolve(__dirname, '../')
// 基础配置

export default defineConfig(({ mode, command, isSsrBuild, isPreview }) => {
  const envDir = resolve(rootPath, './env')
  const envPrefix = 'FAST_'
  const env = loadEnv(mode, envDir, envPrefix)
  return {
    // 环境变量配置
    envDir,
    envPrefix,

    // 插件配置
    plugins: [vue(), versionInfoPlugin({}), analyzer()],

    resolve: {
      alias: {
        'lib-name/export': resolve(rootPath, 'lib-export-path'),
      },
      extensions: ['.ts', '.js', '.tsx', '.jsx', '.json'],
      // 优化模块解析顺序
      mainFields: ['module', 'main', 'browser'],
    },

    // 补充 Vite 自身的转译排除规则
    esbuild: {
      exclude: /node_modules|templates/, // 阻止 esbuild 处理 node_modules 和 templates
    },

    // 优化依赖预构建
    optimizeDeps: {
      // 默认已排除 node_modules，如需额外排除可添加
      // exclude: []
      esbuildOptions: {
        // 禁用 esbuild 的 TypeScript 转译，让 Babel 处理
        tsconfigRaw: {} as any,
      },
    },

    // 开发服务器配置
    server: {
      host: '0.0.0.0',
      headers: {
        // 添加 CSP 头以允许 Web Worker
        'Content-Security-Policy':
          "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:; worker-src 'self' blob:;",
      },
      proxy: {
        '/api': {
          target: 'http://localhost:3000',
          changeOrigin: true,
          rewrite: (path: string) => path.replace(/^\/api/, ''),
        },
      },
    },

    // 构建配置
    build: {
      outDir: 'dist',
      // 当使用 legacy 插件时，让插件处理浏览器兼容性。legacy 插件会根据 .browserslistrc 自动处理现代和旧版浏览器
      // target: 'esnext',
      // 纯 JS 库禁用 CSS 代码分割
      // cssCodeSplit: false,
      // 优化构建报告
      reportCompressedSize: true,
      chunkSizeWarningLimit: 100,
      sourcemap: false,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_debugger: true,
          // 移除未使用的代码
          dead_code: true,
          // 优化条件表达式
          conditionals: true,
          // 移除未使用的变量
          unused: true,
        },
        mangle: {
          // 保留类名和函数名，便于调试
          keep_fnames: false,
          // 保留类名
          keep_classnames: false,
        },
        format: {
          // 保留注释
          comments: false,
        },
      },
      rollupOptions: {
        output: {
          // 确保 ES 模块格式正确
          format: 'es',
          exports: 'named',
          preserveModules: false,
          // 优化代码分割
          // manualChunks: {},
        },
        treeshake: {
          moduleSideEffects: false,
          propertyReadSideEffects: false,
          tryCatchDeoptimization: false,
          // 使用推荐的 tree-shaking 预设
          preset: 'recommended',
          // 自定义 tree-shaking 规则
          unknownGlobalSideEffects: false,
          // 确保 依赖 的 Tree Shaking 正常工作
          annotations: true,
        },
      },
    },
  }
})
