#!/usr/bin/env node

const path = require('path');
const { processJsFiles, checkOllamaHealth } = require('./ollama-console-remover.js');

/**
 * 处理dist目录的便捷脚本
 */
async function processDistDirectory() {
    const rootDir = path.dirname(__dirname); // 回到项目根目录
    const distDir = path.join(rootDir, 'dist');
    const cleanedDir = path.join(rootDir, 'dist-cleaned');

    console.log('🚀 Processing dist directory with Ollama...');
    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, or specify a different directory');
        process.exit(1);
    }

    // 检查Ollama服务
    console.log('🔍 Checking Ollama service...');
    const isOllamaAvailable = await checkOllamaHealth();
    
    if (!isOllamaAvailable) {
        console.log('⚠️  Ollama service is not available');
        console.log('   Starting with local fallback method...');
        console.log('   💡 For better results, start Ollama: ollama serve');
        console.log('   And pull the model: ollama pull deepseek-coder:6.7b');
        console.log('');
    } else {
        console.log('✅ Ollama service is available');
        console.log('');
    }

    try {
        // 先进行dry run预览
        console.log('🔍 Preview mode - checking what will be processed...');
        await processJsFiles(distDir, cleanedDir, isOllamaAvailable, true);
        
        console.log('');
        console.log('🚀 Starting actual processing...');
        
        // 实际处理
        await processJsFiles(distDir, cleanedDir, isOllamaAvailable, false);
        
        console.log('');
        console.log('✅ Processing completed!');
        console.log(`📁 Original directory: ${distDir}`);
        console.log(`📁 Cleaned directory: ${cleanedDir}`);
        console.log('');
        console.log('💡 You can now use the cleaned files from the dist-cleaned directory');
        
        // 显示文件大小对比
        await showSizeComparison(distDir, cleanedDir);
        
    } catch (error) {
        console.error('❌ Error during processing:', error.message);
        process.exit(1);
    }
}

/**
 * 显示处理前后的文件大小对比
 */
async function showSizeComparison(originalDir, cleanedDir) {
    const fs = require('fs');
    
    function getDirectorySize(dir) {
        let totalSize = 0;
        let fileCount = 0;
        let jsSize = 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 {
                    const size = stats.size;
                    totalSize += size;
                    fileCount++;
                    
                    if (path.extname(file) === '.js') {
                        jsSize += size;
                    }
                }
            }
        }
        
        traverse(dir);
        return { totalSize, fileCount, jsSize };
    }
    
    console.log('');
    console.log('📊 Size comparison:');
    
    try {
        const original = getDirectorySize(originalDir);
        const cleaned = getDirectorySize(cleanedDir);
        
        const totalReduction = original.totalSize - cleaned.totalSize;
        const jsReduction = original.jsSize - cleaned.jsSize;
        const totalReductionPercent = ((totalReduction / original.totalSize) * 100).toFixed(2);
        const jsReductionPercent = original.jsSize > 0 ? ((jsReduction / original.jsSize) * 100).toFixed(2) : 0;
        
        console.log(`📁 Total size: ${formatBytes(original.totalSize)} → ${formatBytes(cleaned.totalSize)} (-${totalReductionPercent}% = ${formatBytes(totalReduction)})`);
        console.log(`📄 JS files: ${formatBytes(original.jsSize)} → ${formatBytes(cleaned.jsSize)} (-${jsReductionPercent}% = ${formatBytes(jsReduction)})`);
        console.log(`📝 File count: ${original.fileCount} → ${cleaned.fileCount}`);
        
        if (totalReduction > 0) {
            console.log('✅ Successfully reduced file size!');
        } else {
            console.log('ℹ️  No size reduction (might indicate no console statements were found)');
        }
        
    } catch (error) {
        console.log('⚠️  Could not calculate size comparison:', error.message);
    }
}

/**
 * 格式化字节数为人类可读格式
 */
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];
}

// 执行处理
processDistDirectory().catch(console.error);