/**
 * 修复 account.js v2 - 不使用 beautify
 */
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 (不使用 beautify)...');

// 读取原始代码
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} 个解码映射`);

// 替换字符串 - 按长度排序，先替换长的
const entries = Object.entries(decodeMap).sort((a, b) => b[0].length - a[0].length);

let count = 0;
for (const [pattern, decoded] of entries) {
    // 选择合适的引号
    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, "\\'")}'`;
    }

    // 简单字符串替换（不使用正则，避免问题）
    while (code.includes(pattern)) {
        code = code.replace(pattern, replacement);
        count++;
    }
}
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}`);
