const fs = require('fs');

// 读取原始 provider.js 和已解码的映射
const code = fs.readFileSync('D:/temp/破解/cursorpro-0.4.5/原版本/extension/out/webview/provider.js', 'utf8');
const decodeMap = require('./provider_decoded_map.json');

console.log('文件大小:', code.length, '字节');
console.log('解码映射数量:', Object.keys(decodeMap).length);

let deobfuscated = code;

// 按长度降序排序键，避免部分替换问题
const sortedEntries = Object.entries(decodeMap).sort((a, b) => b[0].length - a[0].length);

let replacedCount = 0;
for (const [pattern, value] of sortedEntries) {
    // 根据内容选择合适的引号
    let replacement;
    if (typeof value !== 'string') {
        replacement = JSON.stringify(value);
    } else if (value.includes('\n') || value.includes('\r') || value.length > 500) {
        // 长字符串或多行字符串用反引号
        replacement = '`' + value.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$/g, '\\$') + '`';
    } else if (value.includes("'") && !value.includes('"')) {
        replacement = JSON.stringify(value);
    } else if (value.includes('"') && !value.includes("'")) {
        replacement = `'${value.replace(/\\/g, '\\\\')}'`;
    } else if (value.includes("'") && value.includes('"')) {
        replacement = JSON.stringify(value);
    } else {
        replacement = `'${value.replace(/\\/g, '\\\\')}'`;
    }

    // 直接替换
    if (deobfuscated.includes(pattern)) {
        deobfuscated = deobfuscated.split(pattern).join(replacement);
        replacedCount++;
    }
}

console.log('替换了', replacedCount, '个模式');

// 移除别名定义
deobfuscated = deobfuscated.replace(/const _0xa6d6ac=_0x56bd;/g, '// [ALIAS REMOVED]');

// 保存
const outputPath = 'D:/temp/破解/cursorpro-0.4.5/deobfuscated/provider/provider.js';
fs.mkdirSync('D:/temp/破解/cursorpro-0.4.5/deobfuscated/provider', { recursive: true });
fs.writeFileSync(outputPath, deobfuscated);
console.log('已保存到:', outputPath);

// 检查是否还有未替换的调用
const remaining = deobfuscated.match(/_0x[a-f0-9]+\(0x[a-f0-9]+,'[^']+'\)/g) || [];
console.log('剩余未替换调用:', remaining.length);
if (remaining.length > 0 && remaining.length < 20) {
    console.log('示例:', remaining.slice(0, 5));
}

// 输出一些关键字符串位置
console.log('\n=== 搜索关键API ===');
const cursorShPos = deobfuscated.indexOf('cursor.sh');
const api2Pos = deobfuscated.indexOf('api2.cursor.sh');
const api3Pos = deobfuscated.indexOf('api3.cursor.sh');
console.log('cursor.sh 位置:', cursorShPos);
console.log('api2.cursor.sh 位置:', api2Pos);
console.log('api3.cursor.sh 位置:', api3Pos);

if (api2Pos !== -1) {
    console.log('\napi2 上下文:');
    console.log(deobfuscated.substring(api2Pos - 100, api2Pos + 150));
}

// 搜索 client 引用
const clientPos = deobfuscated.indexOf('../api/client');
console.log('\n../api/client 位置:', clientPos);
if (clientPos !== -1) {
    console.log('client 上下文:');
    console.log(deobfuscated.substring(clientPos - 50, clientPos + 200));
}
