#!/usr/bin/env node

const path = require('path');
const { processDirectory } = require('./optimized-processor.js');

/**
 * 优化处理dist目录的便捷脚本
 */
async function optimizeDist() {
    const rootDir = path.dirname(__dirname); // 项目根目录
    const distDir = path.join(rootDir, 'dist');
    
    console.log('🚀 Optimized Dist Processor');
    console.log('========================');
    console.log('');
    
    // 检查dist目录
    const fs = require('fs');
    if (!fs.existsSync(distDir)) {
        console.error(`❌ Dist directory not found: ${distDir}`);
        console.log('💡 Make sure to build your project first');
        process.exit(1);
    }
    
    console.log(`📂 Processing dist directory: ${distDir}`);
    console.log('');
    
    try {
        // 使用优化处理器处理dist目录
        const result = await processDirectory(distDir, {
            useOllama: true,        // 优先使用Ollama
            parallel: true,         // 并行处理
            dryRun: false,          // 实际处理文件
            clearCache: false       // 保留缓存
        });
        
        console.log('');
        console.log('🎉 Optimization completed!');
        console.log('=========================');
        console.log('');
        console.log('📁 Results:');
        console.log(`   Original: ${distDir}`);
        console.log(`   Optimized: ${result.outputDir}`);
        console.log('');
        console.log('📊 Statistics:');
        console.log(`   Total files: ${result.totalFiles}`);
        console.log(`   Successful: ${result.successful}`);
        console.log(`   Failed: ${result.failed}`);
        console.log(`   Size saved: ${result.totalReduction > 0 ? formatBytes(result.totalReduction) : 'No reduction'}`);
        console.log(`   Processing time: ${result.processingTime.toFixed(2)}s`);
        console.log('');
        
        if (result.totalReduction > 0) {
            const reductionPercent = ((result.totalReduction / getTotalSize(distDir)) * 100).toFixed(2);
            console.log(`📈 Performance improvement: ${reductionPercent}% size reduction`);
        }
        
        console.log('💡 Usage:');
        console.log(`   Use files from: ${result.outputDir}`);
        console.log('   Cache stored in: ./scripts/.cache/');
        console.log('   Run with --dry-run to preview changes');
        
    } catch (error) {
        console.error('❌ Optimization failed:', error.message);
        process.exit(1);
    }
}

/**
 * 获取目录总大小
 */
function getTotalSize(dir) {
    const fs = require('fs');
    let totalSize = 0;
    
    function traverse(currentDir) {
        const files = fs.readdirSync(currentDir);
        
        for (const file of files) {
            const filePath = path.join(currentDir, file);
            const stats = fs.statSync(filePath);
            
            if (stats.isDirectory()) {
                traverse(filePath);
            } else {
                totalSize += stats.size;
            }
        }
    }
    
    traverse(dir);
    return totalSize;
}

/**
 * 格式化字节数
 */
function formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 解析命令行参数
const args = process.argv.slice(2);
const options = {};

for (let i = 0; i < args.length; i++) {
    const arg = args[i];
    
    if (arg === '--help' || arg === '-h') {
        console.log(`
Usage: node optimize-dist.js [options]

Options:
  --help, -h          Show this help message
  --dry-run, -d       Preview mode - don't save files
  --local, -l         Use local fallback method instead of Ollama
  --single, -s        Use single-threaded processing
  --clear-cache, -c   Clear existing cache before processing

Description:
  Optimizes all JavaScript files in the dist directory by:
  🤖 Removing console statements using Ollama AI
  🚀 Parallel processing for faster execution
  📋 Intelligent caching to avoid reprocessing
  ⏭️  Incremental processing of only changed files
  📊 Detailed performance statistics

Examples:
  node optimize-dist.js                    # Full optimization
  node optimize-dist.js --dry-run          # Preview changes
  node optimize-dist.js --local            # Use local method
  node optimize-dist.js --clear-cache      # Clear cache and reprocess
`);
        process.exit(0);
    } else if (arg === '--dry-run' || arg === '-d') {
        options.dryRun = true;
    } else if (arg === '--local' || arg === '-l') {
        options.useOllama = false;
    } else if (arg === '--single' || arg === '-s') {
        options.parallel = false;
    } else if (arg === '--clear-cache' || arg === '-c') {
        options.clearCache = true;
    }
}

// 执行优化
optimizeDist(options).catch(console.error);