import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'node:path';
import fs from 'node:fs';

// 解析命令行参数
const args = process.argv.slice(2); // 去掉 "node" 和脚本路径
const nameArgIndex = args.findIndex(arg => arg === '--name');
const libName = nameArgIndex !== -1 ? args[nameArgIndex + 1] : '';
const componentsEnv = libName !== 'undefined' ? libName : ''
console.log('c111omponentsEnv', libName);

// 配置构建
export default defineConfig(() => {
  const entryFile = componentsEnv ? `src/components/${libName}/index.ts` : `src/components/index.ts`;

  return {
    server: {
      proxy: {
        '/api': {
          target: 'http://127.0.0.1:9090',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path
        }
      }
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },
    build: {
      outDir: `dist/${componentsEnv}`,
      // emptyOutDir: false,  // 不清空输出目录，因为我们要构建多个组件
      lib: {
        entry: path.resolve(__dirname, entryFile),
        name: componentsEnv || 'default', //全局声明
        fileName: (format) => `index.${format}.js`,
        formats: ['es', 'umd'],
      },
      rollupOptions: {
        external: [
          // React 及其相关
        'react',
        'react-dom',
        'react/jsx-runtime',
        /^react\/.+$/, // 匹配所有 react/ 开头的依赖

        // Ant Design 及其相关
        'antd',
        /^antd\/.+$/,  // 匹配所有 antd/ 开头的依赖
        '@ant-design',
        /^@ant-design\/.+$/, // 匹配所有 @ant-design/ 开头的依赖

        // 其他指定库
        '@craftjs/core',
        /^@craftjs\/.+$/, // 匹配所有 @craftjs/ 开头的依赖
        ],
        output: {
          globals: {
           'react': 'React',
          'react-dom': 'ReactDOM',
          'antd': 'antd',
          'react/jsx-runtime': 'jsx',
          '@ant-design/pro-components': 'ProComponents',
          '@craftjs/core': 'CraftjsCore',
          },
          interop: 'auto'
        },
        // 添加这个配置来排除公共资源
        input: {
          main: path.resolve(__dirname, entryFile)
        }
      },
      // 禁用复制public下的文件
      copyPublicDir: false
    },
     plugins: [
      react({}),
    ],
    css: {
      preprocessorOptions: {
        less: {
          modules: {
            localsConvention: 'camelCase' // 或 'dashes'
          }
        }
      }
    }
  };
});