import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
import fs from 'fs-extra'

// 复制 Monaco Editor 的资源文件
const copyMonacoEditorFiles = () => {
    return {
        name: 'copy-monaco-editor',
        buildStart() {
            const monacoPath = path.resolve(__dirname, 'node_modules/monaco-editor/min/vs')
            const targetPath = path.resolve(__dirname, 'public/monaco-editor/min/vs')
            if (!fs.existsSync(targetPath)) {
                fs.copySync(monacoPath, targetPath)
            }
        }
    }
}

export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')
  
  // 开发环境代理目标地址（可通过环境变量配置）
  const proxyTarget = env.VITE_PROXY_TARGET || 'http://localhost:8080'

  return {
    plugins: [
      react(),
      copyMonacoEditorFiles()
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src')
      }
    },
    build: {
      rollupOptions: {
        output: {
          manualChunks(id) {
            // 将 node_modules 分包
            if (id.includes('node_modules')) {
              // React 核心库必须单独打包，避免重复引用
              if (id.includes('react') || id.includes('react-dom') || id.includes('scheduler')) {
                return 'react-vendor';
              }
              // 将大型库单独打包
              if (id.includes('react-flow') || id.includes('@xyflow')) {
                return 'react-flow';
              }
              if (id.includes('antd') || id.includes('@ant-design')) {
                return 'antd';
              }
              if (id.includes('@radix-ui')) {
                return 'radix-ui';
              }
              if (id.includes('monaco-editor') || id.includes('@monaco-editor')) {
                return 'monaco-editor';
              }
              // 其他 node_modules 库打包到 vendor
              return 'vendor';
            }
          }
        }
      }
    },
    server: {
      port: 3000,
      proxy: {
        '/api': {
          target: proxyTarget,
          changeOrigin: true,
          ws: true, // 支持WebSocket代理
          // 打印代理信息
          configure: (proxy, _options) => {
            proxy.on('error', (err, _req, _res) => {
              console.log('代理错误', err);
            });
            proxy.on('proxyReq', (proxyReq, req, _res) => {
              console.log('📡 代理请求:', req.method, req.url, '→', proxyTarget);
            });
            proxy.on('proxyReqWs', (proxyReq, req, socket, options, head) => {
              console.log('🔌 WebSocket代理:', req.url, '→', proxyTarget);
            });
          }
        },
        '/actuator': {
          target: proxyTarget,
          changeOrigin: true,
          // 打印代理信息
          configure: (proxy, _options) => {
            proxy.on('error', (err, _req, _res) => {
              console.log('Actuator 代理错误', err);
            });
            proxy.on('proxyReq', (proxyReq, req, _res) => {
              console.log('📊 Actuator 代理请求:', req.method, req.url, '→', proxyTarget);
            });
          }
        }
      },
      fs: {
        strict: false,
        allow: ['..']
      }
    }
  }
}) 