import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
// import electron from 'vite-plugin-electron'
// import vueDevTools from 'vite-plugin-vue-devtools'

import mkcert from "vite-plugin-mkcert";
// https://vite.dev/config/
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd())
  console.log('\x1b[36m%s\x1b[0m', '[VITE_APP_ENV]', env.VITE_APP_ENV)
  console.log('\x1b[33m%s\x1b[0m', '[VITE_APP_BASE_API]', env.VITE_APP_BASE_API)
  
  // 将环境变量转换为 process.env 格式
  const processEnv = {}
  Object.keys(env).forEach(key => {
    processEnv[key] = JSON.stringify(env[key])
  })

  // 始终启用mock
  const isMockEnabled = true

  return {
    plugins: [
      vue(),
      mkcert({
        source: 'coding',
        autoUpgrade: true,
        force: true,
      }),
      // electron({
      //   entry: 'electron/main.js',
      // }),
      // vueDevTools(),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler'
        }
      }
    },
    server: {
      host: true,
      port: 31003,
      https: true,
      cors: true,
      proxy: {
        '/api': {
          target: env.VITE_APP_BASE_API,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
          secure: false,
          configure: (proxy, options) => {
            // proxy.on('proxyReq', (proxyReq, req, res) => {
            //   const targetOrigin = new URL(env.VITE_APP_BASE_API).origin;
            //   proxyReq.setHeader('Origin', targetOrigin);
              
            //   if (req.originalUrl && req.originalUrl.includes('chat-messages')) {
            //     proxyReq.setHeader('Accept', 'text/event-stream');
            //   }
            // });
            // proxy.on('proxyRes', (proxyRes, req, res) => {
            //   if (req.originalUrl && req.originalUrl.includes('chat-messages')) {
            //     proxyRes.headers['content-type'] = 'text/event-stream';
            //     proxyRes.headers['Cache-Control'] = 'no-cache';
            //     proxyRes.headers['Connection'] = 'keep-alive';
            //   }
            // });
          }
        }
      }
    },
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            'vendor': ['vue', 'vue-router', 'pinia']
          }
        }
      },
      chunkSizeWarningLimit: 1500,
      terserOptions: {
        compress: {
          // drop_console: true,
          drop_debugger: true
        }
      }
    },
    define: {
      'process.env': processEnv,
      // 注入mock环境变量
      'import.meta.env.VITE_APP_MOCK': JSON.stringify(isMockEnabled)
    }
  }
})
