import path from 'path';
import fs from 'fs';
let currentTheme: Record<string, string> = {};

// 初始化主题
export async function initializeTheme(themeMode: string = 'default') {
  try {
    const theme = (await import(`@/styles/theme.${themeMode}.mjs`)).default;
    currentTheme = { ...theme };
    refreshViteInjectedVariables(); // 刷新 Vite 变量
    console.log(`Initialized theme: ${themeMode}`);
  } catch (error) {
    console.error(`Failed to initialize theme: ${themeMode}`, error);
  }
}

// 动态切换主题
export async function switchTheme(themeMode: string) {
  try {
    const newTheme = (await import(`@/styles/theme.${themeMode}.mjs`)).default;
    currentTheme = { ...newTheme };
    refreshViteInjectedVariables(); // 刷新 Vite 变量
    console.log(`Switched to theme: ${themeMode}`);
  } catch (error) {
    console.error(`Failed to switch theme to ${themeMode}:`, error);
  }
}

// 更新单个主题变量
export function updateThemeVariable(key: string, value: string) {
  currentTheme[key] = value;
  refreshViteInjectedVariables(); // 刷新 Vite 变量
  console.log(`Updated ${key} to ${value}`);
}

// 刷新 Vite 的动态变量注入
function refreshViteInjectedVariables() {
  const lessContent = generateLessVariables(currentTheme);
  const stylusContent = generateStylusVariables(currentTheme);

  fs.writeFileSync(
    path.resolve(__dirname, '../styles/_generated-theme.less'), // 确保路径正确
    lessContent,
  );
  fs.writeFileSync(
    path.resolve(__dirname, '../styles/_generated-theme.styl'), // 确保路径正确
    stylusContent,
  );

  if (import.meta.hot) {
    import.meta.hot.invalidate(); // 触发 Vite 热更新
  }
}

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

// 工具函数：生成 Stylus 变量
function generateStylusVariables(theme: Record<string, string>) {
  return Object.entries(theme)
    .map(([key, value]) => `$${key.replace(/([A-Z])/g, '-$1').toLowerCase()} = ${value}`)
    .join('\n');
}
