/**
 * 批量修复所有文件 - 使用安全的单次替换
 */
const fs = require('fs');
const path = require('path');

const baseDir = 'D:/temp/破解/cursorpro-0.4.5';
const outputDir = path.join(baseDir, 'deobfuscated_full/extension/out');

function ensureDir(dir) {
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
    }
}

function processFile(inputPath, outputPath, mapPath, filename) {
    console.log(`\n${'='.repeat(50)}`);
    console.log(`处理: ${filename}`);
    console.log('='.repeat(50));

    // 读取原始代码
    let code = fs.readFileSync(inputPath, 'utf8');
    console.log(`原始大小: ${(code.length / 1024).toFixed(2)} KB`);

    // 加载解码映射
    if (!fs.existsSync(mapPath)) {
        console.log('映射文件不存在，跳过');
        return;
    }
    const decodeMap = JSON.parse(fs.readFileSync(mapPath, 'utf8'));
    console.log(`加载了 ${Object.keys(decodeMap).length} 个解码映射`);

    // 使用 split/join 进行安全替换
    let count = 0;
    for (const [pattern, decoded] of Object.entries(decodeMap)) {
        // 选择合适的引号
        let replacement;
        if (decoded.includes('\n') || decoded.includes('\r')) {
            replacement = '`' + decoded.replace(/`/g, '\\`').replace(/\$/g, '\\$') + '`';
        } else if (decoded.includes("'") && !decoded.includes('"')) {
            replacement = JSON.stringify(decoded);
        } else {
            replacement = `'${decoded.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
        }

        const newCode = code.split(pattern).join(replacement);
        if (newCode !== code) {
            count++;
            code = newCode;
        }
    }
    console.log(`替换了 ${count} 个不同的模式`);

    // 简单清理
    code = code.replace(/\['([a-zA-Z_$][a-zA-Z0-9_$]*)'\]/g, '.$1');
    code = code.replace(/!!\[\]/g, 'true');
    code = code.replace(/!\[\]/g, 'false');

    console.log(`处理后大小: ${(code.length / 1024).toFixed(2)} KB`);

    // 保存
    ensureDir(path.dirname(outputPath));
    fs.writeFileSync(outputPath, code);
    console.log(`已保存: ${outputPath}`);
}

// 主函数
function main() {
    console.log('╔════════════════════════════════════════════════════╗');
    console.log('║             批量修复所有文件                         ║');
    console.log('║           使用安全的单次替换方法                      ║');
    console.log('╚════════════════════════════════════════════════════╝');

    const files = [
        {
            input: '原版本/extension/out/webview/provider.js',
            output: 'webview/provider.js',
            map: 'provider_decoded_map.json'
        },
        {
            input: '原版本/extension/out/extension.js',
            output: 'extension.js',
            map: 'extension_decoded_map.json'
        },
        {
            input: '原版本/extension/out/utils/account.js',
            output: 'utils/account.js',
            map: 'account_decoded_map.json'
        },
        {
            input: '原版本/extension/out/utils/sqlite.js',
            output: 'utils/sqlite.js',
            map: 'sqlite_decoded_map.json'
        },
        {
            input: '原版本/extension/out/api/client.js',
            output: 'api/client.js',
            map: 'client_decoded_map.json'
        }
    ];

    for (const file of files) {
        const inputPath = path.join(baseDir, file.input);
        const outputPath = path.join(outputDir, file.output);
        const mapPath = path.join(baseDir, file.map);

        if (fs.existsSync(inputPath)) {
            processFile(inputPath, outputPath, mapPath, file.input);
        } else {
            console.log(`\n跳过: ${file.input} (不存在)`);
        }
    }

    console.log('\n╔════════════════════════════════════════════════════╗');
    console.log('║                    完成！                            ║');
    console.log('╚════════════════════════════════════════════════════╝');
    console.log(`\n输出目录: ${outputDir}`);
}

main();
