import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import * as fs from 'fs';
import * as dotenv from 'dotenv';
import progress from 'vite-plugin-progress';
import colors from 'picocolors';
// import pluginBasicSsl from '@vitejs/plugin-basic-ssl';

// https://vitejs.dev/config/
export default defineConfig(() => {
  const NODE_ENV = process.env.NODE_ENV || 'development';
  const envFiles = [`.env.${NODE_ENV}`];
  for (const file of envFiles) {
    const envConfig = dotenv.parse(fs.readFileSync(file));
    // eslint-disable-next-line guard-for-in
    for (const k in envConfig) {
      process.env[k] = envConfig[k];
    }
  }

  return {
    plugins: [
      react(),
      // pluginBasicSsl(),
      progress({
        format: `${colors.green(colors.bold('Bouilding'))} ${colors.cyan('[:bar]')} :percent`,
      }),
    ],
    server: {
      port: 5178,
      host: '0.0.0.0',
      strictPort: true,
      open: true,
      https: false,
      hmr: {
        overlay: true,
      },
      proxy: {
        '/api': {
          target: process.env.VITE_API_URL_WORD,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''), // 将请求路径中的“/api”前缀替换为空字符串
        },
        '/openapi': {
          target: process.env.VITE_API_OPENAI_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/openapi/, '/openapi'), // 将请求路径中的“/api”前缀替换为空字符串
        },
      },
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
        '@/public': path.resolve(__dirname, './public'),
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
        },
      },
    },
    optimizeDeps: {},
    build: {
      // rollupOptions: {
      //   external: ['easy-formula-editor'],
      // },
      // rollupOptions: {
      //   external: ['highlight.js'],
      // },
      commonjsOptions: {},
      sourcemap: false,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
    },
  };
});
