import { readdirSync, readFileSync, writeFileSync, existsSync, mkdirSync, statSync } from 'fs';
import { resolve, join, extname, dirname } from 'path';
import less from 'less';

// Vite插件用于预处理场景样式
export function sceneStylePlugin() {
  let compiledStyles = '';
  
  return {
    name: 'scene-style-processor',
    
    // 在构建开始前执行
    async buildStart() {
      console.log('Processing scene styles...');
      
      // 扫描所有场景目录
      const templateDir = resolve(__dirname, '../../template-example/sence');
      if (!existsSync(templateDir)) {
        console.log('Scene directory not found');
        return;
      }
      
      // 确保style目录存在
      const styleDir = resolve(__dirname, '../../template-example/style');
      if (!existsSync(styleDir)) {
        mkdirSync(styleDir, { recursive: true });
      }
      
      // 递归扫描场景目录
      const processDirectory = (dirPath, relativePath = '') => {
        const items = readdirSync(dirPath);
        
        items.forEach(item => {
          const itemPath = join(dirPath, item);
          const itemStat = statSync(itemPath);
          
          if (itemStat.isDirectory()) {
            // 递归处理子目录
            processDirectory(itemPath, join(relativePath, item));
          } else if (extname(item) === '.less') {
            // 处理.less文件
            try {
              const lessContent = readFileSync(itemPath, 'utf-8');
              
              // 编译Less到CSS
              less.render(lessContent, (err, result) => {
                if (err) {
                  console.error('Less compilation error:', err);
                  return;
                }
                
                // 为每个场景样式添加注释标识
                const scenePath = join(relativePath, item.replace('.less', ''));
                const cssWithComment = `\n/* Scene style for ${scenePath} */\n${result.css}\n`;
                
                // 累积所有样式
                compiledStyles += cssWithComment;
                console.log(`Compiled style: ${scenePath}`);
              });
            } catch (error) {
              console.error(`Error processing ${itemPath}:`, error);
            }
          }
        });
      };
      
      // 开始处理
      processDirectory(templateDir);
      
      // 立即生成CSS文件，确保在构建过程中可用
      if (compiledStyles) {
        const outputPath = resolve(__dirname, '../../template-example/style/scene-styles.css');
        const outputContent = `/* Auto-generated scene styles */\n${compiledStyles}`;
        writeFileSync(outputPath, outputContent, 'utf-8');
        console.log(`Scene styles written to: ${outputPath}`);
      }
    }
  };
}