#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

// 简单的语法检查函数
function hasSyntaxErrors(code) {
    const lines = code.split('\n');
    
    for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();
        
        // 检查常见的语法错误模式
        if (line.includes('p[s][0]') && !line.includes('p[s][0];')) {
            console.log(`Syntax error detected at line ${i + 1}: missing semicolon after p[s][0]`);
            return true;
        }
        
        // 检查未闭合的括号（简单检查）
        const openBrackets = (line.match(/\[/g) || []).length;
        const closeBrackets = (line.match(/\]/g) || []).length;
        if (Math.abs(openBrackets - closeBrackets) > 2) {
            console.log(`Bracket mismatch detected at line ${i + 1}`);
            return true;
        }
        
        // 检查其他常见错误模式
        if (line.includes('void 0)') && line.includes('if(')) {
            console.log(`Conditional syntax error detected at line ${i + 1}`);
            return true;
        }
    }
    
    return false;
}

// 简单的console移除函数
function removeConsoleLocally(jsCode) {
    return jsCode
        .replace(/console\.(log|error|warn|info|debug|assert|trace|table|group|groupEnd|time|timeEnd)\s*\([^;]*?\);?\s*/g, '')
        .replace(/\/\*[\s\S]*?\*\//g, '')
        .replace(/\/\/.*$/gm, '');
}

// 测试runtime.js文件
async function testRuntimeProcessing() {
    console.log('🧪 Testing Runtime.js with Simple Processor');
    console.log('==========================================');
    
    const runtimePath = path.join(__dirname, '../../dist/common/runtime.js');
    
    if (!fs.existsSync(runtimePath)) {
        console.log('❌ runtime.js file not found');
        return;
    }
    
    try {
        const originalCode = fs.readFileSync(runtimePath, 'utf8');
        console.log(`📄 Original file size: ${originalCode.length} characters`);
        
        // 检查语法错误
        const hasError = hasSyntaxErrors(originalCode);
        
        if (hasError) {
            console.log('⚠️  Syntax error detected - file would be skipped in parallel processing');
        } else {
            console.log('✅ No syntax errors detected');
            
            // 尝试处理
            const cleanedCode = removeConsoleLocally(originalCode);
            console.log(`🧹 Cleaned file size: ${cleanedCode.length} characters`);
            console.log(`📉 Size reduction: ${originalCode.length - cleanedCode.length} characters`);
        }
        
        console.log('\n✅ Simple processing test completed!');
        
    } catch (error) {
        console.error('❌ Error processing runtime.js:', error.message);
    }
}

testRuntimeProcessing();