import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import Components from 'unplugin-vue-components/vite';
import AutoImport from 'unplugin-auto-import/vite';
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';
import path from 'path';
import customLoaderPlugin from './customLoaderPlugin';

// 当前主题的存储
let currentTheme: Record<string, string> = {};

// 动态生成 Less 和 Stylus 的变量
function generateLessVariables(theme: Record<string, string>) {
  return Object.entries(theme)
    .map(([key, value]) => `@${key.replace(/([A-Z])/g, '-$1').toLowerCase()}: ${value};`)
    .join('\n');
}

function generateStylusVariables(theme: Record<string, string>) {
  return Object.entries(theme)
    .map(([key, value]) => `$${key.replace(/([A-Z])/g, '-$1').toLowerCase()} = ${value}`)
    .join('\n');
}

// 动态加载主题文件
async function loadTheme(themeMode: string) {
  const themePath = path.resolve(__dirname, `src/styles/theme.${themeMode}.mjs`);
  return (await import(themePath)).default; // 使用动态导入加载主题文件
}

export default defineConfig(async ({ mode }) => {
  const actualMode = mode || '';
  const env = loadEnv(actualMode, process.cwd(), 'VITE_');
  const themeMode = env.VITE_THEME_MODE || 'default';

  // 初始化主题
  currentTheme = await loadTheme(themeMode);

  return {
    plugins: [
      vue(),
      // customLoaderPlugin(),

      Components({
        resolvers: [AntDesignVueResolver()],
        dts: 'src/components.d.ts',
      }),
      AutoImport({
        imports: ['vue', 'vue-router'],
        resolvers: [AntDesignVueResolver()],
        dts: 'src/auto-imports.d.ts',
      }),
    ],
    css: {
      postcss: './postcss.config.js',
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          additionalData: generateLessVariables(currentTheme),
        },
        stylus: {
          additionalData: generateStylusVariables(currentTheme),
        },
      },
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },
  };
});
