/**
 * 修复 account.js v3 - 安全的单次替换
 */
const fs = require('fs');
const path = require('path');

const baseDir = 'D:/temp/破解/cursorpro-0.4.5';
const inputPath = path.join(baseDir, '原版本/extension/out/utils/account.js');
const outputPath = path.join(baseDir, 'deobfuscated_full/extension/out/utils/account.js');
const mapPath = path.join(baseDir, 'account_decoded_map.json');

console.log('修复 account.js v3...');

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

// 加载解码映射
const decodeMap = JSON.parse(fs.readFileSync(mapPath, 'utf8'));
console.log(`加载了 ${Object.keys(decodeMap).length} 个解码映射`);

// 使用全局正则进行单次替换
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 escapedPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

    // 使用 replaceAll 或 split/join 进行安全替换
    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`);

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