/**
 * 修复变量赋值错误（逻辑 bug）
 * 这些是反混淆过程中产生的变量名替换错误
 */
const fs = require('fs');

const inputPath = 'D:/temp/破解/cursorpro-0.4.5/deobfuscated_full/extension/out/webview/provider.js';
let code = fs.readFileSync(inputPath, 'utf8');

console.log('修复变量赋值错误...\n');

// 定义需要修复的 bug
const bugFixes = [
    // _handleToggleProxy 中 content 被错误赋值为 usageData
    {
        desc: '_handleToggleProxy: usageData -> content',
        fixes: [
            { old: 'usageData = content.substring(0, index) + content.substring(index1 + this.HOSTS_MARKER_END.length);',
              new: 'content = content.substring(0, index) + content.substring(index1 + this.HOSTS_MARKER_END.length);' },
            { old: 'usageData = content.replace(/\\n{3,}/g, "\\n\\n").trim();',
              new: 'content = content.replace(/\\n{3,}/g, "\\n\\n").trim();' },
            { old: 'usageData += result;',
              new: 'content += result;' }
        ]
    },

    // _handleRestoreSeamless 中 fileContent 被错误赋值为 checkResult
    {
        desc: '_handleRestoreSeamless: checkResult -> fileContent',
        fixes: [
            { old: 'checkResult = fileContent.replace("_showNotification(){/*i0*/}_showNotificationOld(){"',
              new: 'fileContent = fileContent.replace("_showNotification(){/*i0*/}_showNotificationOld(){"' },
            { old: 'checkResult = fileContent.substring(0, index) + fileContent.substring(index1 + 7);',
              new: 'fileContent = fileContent.substring(0, index) + fileContent.substring(index1 + 7);' },
            { old: 'checkResult = fileContent.substring(0, index2) + fileContent.substring(index3 + 7);',
              new: 'fileContent = fileContent.substring(0, index2) + fileContent.substring(index3 + 7);' }
        ]
    },

    // _handleInjectSeamless 中 fileContent 被错误赋值为 announcementData
    {
        desc: '_handleInjectSeamless: announcementData -> fileContent',
        fixes: [
            { old: 'announcementData = fileContent.replace(linuxPath.scode, linuxPath.replacement);',
              new: 'fileContent = fileContent.replace(linuxPath.scode, linuxPath.replacement);' }
        ]
    },

    // _getWorkbenchPathSync 中 items 被错误赋值为 usageResponse
    {
        desc: '_getWorkbenchPathSync: usageResponse -> items',
        fixes: [
            { old: 'usageResponse = ["/Applications/Cursor.app/Contents/Resources/app/out/vs/workbench/workbench.desktop.main.js"];',
              new: 'items = ["/Applications/Cursor.app/Contents/Resources/app/out/vs/workbench/workbench.desktop.main.js"];' },
            { old: 'usageResponse = ["/opt/Cursor/resources/app/out/vs/workbench/workbench.desktop.main.js", \'/usr/share/cursor/resources/app/out/vs/workbench/workbench.desktop.main.js\'];',
              new: 'items = ["/opt/Cursor/resources/app/out/vs/workbench/workbench.desktop.main.js", \'/usr/share/cursor/resources/app/out/vs/workbench/workbench.desktop.main.js\'];' }
        ]
    },

    // _handleInjectSeamless 中 errorMsg 被错误赋值为 currentVersion
    {
        desc: '_handleInjectSeamless: currentVersion -> errorMsg',
        fixes: [
            { old: 'currentVersion = "没有写入权限，请在终端执行: sudo chmod -R 777 /Applications/Cursor.app";',
              new: 'errorMsg = "没有写入权限，请在终端执行: sudo chmod -R 777 /Applications/Cursor.app";' },
            { old: 'currentVersion = "没有写入权限，请使用 sudo 权限运行或修改文件权限";',
              new: 'errorMsg = "没有写入权限，请使用 sudo 权限运行或修改文件权限";' }
        ]
    },

    // _writeHostsFile 中 isFalse 被错误赋值为 remainingCount
    {
        desc: '_writeHostsFile: remainingCount -> isFalse',
        fixes: [
            { old: 'remainingCount = true;',
              new: 'isFalse = true;' }
        ]
    },

    // _handleGetCursorRunningPath 中变量名错误
    {
        desc: '_handleGetCursorRunningPath: platformPath/appPath -> filePath/str',
        fixes: [
            { old: 'platformPath = configValue;',
              new: 'filePath = configValue;' },
            { old: 'appPath = path.join(configValue, "Contents", "Resources", "app", "package.json");',
              new: 'str = path.join(configValue, "Contents", "Resources", "app", "package.json");' },
            { old: 'appPath = path.join(configValue, "resources", "app", "package.json");',
              new: 'str = path.join(configValue, "resources", "app", "package.json");' },
            { old: 'platformPath = path.dirname(trimmed);',
              new: 'filePath = path.dirname(trimmed);' },
            { old: 'appPath = path.join(filePath, "resources", "app", "package.json");',
              new: 'str = path.join(filePath, "resources", "app", "package.json");' },
            { old: 'platformPath = originalCode;',
              new: 'filePath = originalCode;' },
            { old: 'appPath = joinedPath;',
              new: 'str = joinedPath;' },
            { old: 'platformPath = (await this._getCursorInstallPath()) || "/Applications/Cursor.app";',
              new: 'filePath = (await this._getCursorInstallPath()) || "/Applications/Cursor.app";' },
            { old: 'appPath = path.join(filePath, "Contents", "Resources", \'app\', "package.json");',
              new: 'str = path.join(filePath, "Contents", "Resources", \'app\', "package.json");' },
            { old: 'platformPath = backupDir;',
              new: 'filePath = backupDir;' },
            { old: 'appPath = path.join(backupDir, "resources", \'app\', "package.json");',
              new: 'str = path.join(backupDir, "resources", \'app\', "package.json");' },
            { old: 'seamlessDir = parsed.version || \'\';',
              new: 'str1 = parsed.version || \'\';' }
        ]
    },

    // _handleGetCursorPath 中变量名错误
    {
        desc: '_handleGetCursorPath: backupPath/modifiedCode/injectionCode -> str/str1/str2',
        fixes: [
            { old: 'backupPath = path.dirname(trimmed);',
              new: 'str = path.dirname(trimmed);' },
            { old: 'backupPath = path.dirname(lineContent.trim());',
              new: 'str = path.dirname(lineContent.trim());' },
            { old: 'modifiedCode = path.join(condition, "Cursor");',
              new: 'str1 = path.join(condition, "Cursor");' },
            { old: 'backupPath = matchResult[1];',
              new: 'str = matchResult[1];' },
            { old: 'backupPath = path.dirname(trimmed);',
              new: 'str = path.dirname(trimmed);' },
            { old: 'modifiedCode = path.join(condition, \'Library\', "Application Support", "Cursor");',
              new: 'str1 = path.join(condition, \'Library\', "Application Support", "Cursor");' },
            { old: 'backupPath = path.dirname(e35.trim());',
              new: 'str = path.dirname(e35.trim());' },
            { old: 'modifiedCode = path.join(condition, ".config", "Cursor");',
              new: 'str1 = path.join(condition, ".config", "Cursor");' },
            { old: 'backupPath = "未检测到运行中的Cursor进程";',
              new: 'str = "未检测到运行中的Cursor进程";' },
            { old: 'injectionCode = path.join(str, \'resources\', "app", \'out\', \'vs\', \'workbench\', "workbench.desktop.main.js");',
              new: 'str2 = path.join(str, \'resources\', "app", \'out\', \'vs\', \'workbench\', "workbench.desktop.main.js");' },
            { old: 'injectionCode = path.join(str, "Contents", "Resources", "app", "out", \'vs\', "workbench", \'workbench.desktop.main.js\');',
              new: 'str2 = path.join(str, "Contents", "Resources", "app", "out", \'vs\', "workbench", \'workbench.desktop.main.js\');' },
            { old: 'injectionCode = path.join(str, "resources", "app", "out", \'vs\', "workbench", "workbench.desktop.main.js");',
              new: 'str2 = path.join(str, "resources", "app", "out", \'vs\', "workbench", "workbench.desktop.main.js");' },
            { old: 'injectionCode = (await this._getWorkbenchPathAsync()) || "未找到";',
              new: 'str2 = (await this._getWorkbenchPathAsync()) || "未找到";' }
        ]
    },

    // _getCursorInstallPath 中 result 被错误赋值为 cursorPath
    {
        desc: '_getCursorInstallPath: cursorPath -> result',
        fixes: [
            { old: 'cursorPath = path.dirname(trimmed);',
              new: 'result = path.dirname(trimmed);' },
            { old: 'cursorPath = path.dirname(psOut.trim());',
              new: 'result = path.dirname(psOut.trim());' },
            { old: 'cursorPath = matchResult[1].trim();',
              new: 'result = matchResult[1].trim();' },
            { old: 'cursorPath = matchResult[1];',
              new: 'result = matchResult[1];' },
            { old: 'cursorPath = path.dirname(lnkOut.trim());',
              new: 'result = path.dirname(lnkOut.trim());' },
            { old: 'cursorPath = cursorDbPath;',
              new: 'result = cursorDbPath;' },
            { old: 'cursorPath = "/Applications/Cursor.app";',
              new: 'result = "/Applications/Cursor.app";' },
            { old: 'cursorPath = path.dirname(result);',
              new: 'result = path.dirname(result);' },
            { old: 'cursorPath = statusInfo;',
              new: 'result = statusInfo;' },
            { old: 'cursorPath = childPath.trim();',
              new: 'result = childPath.trim();' }
        ]
    },

    // _handleGetUserSwitchStatus 中 isFalse 被错误赋值为 runningPathData
    {
        desc: '_handleGetUserSwitchStatus: runningPathData -> isFalse',
        fixes: [
            { old: 'runningPathData = status1.is_injected || false;',
              new: 'isFalse = status1.is_injected || false;' }
        ]
    },

    // _getNonce 中 str 被错误赋值为 finalContent
    {
        desc: '_getNonce: finalContent -> str',
        fixes: [
            { old: 'finalContent += items.charAt(Math.floor(Math.random() * items.length));',
              new: 'str += items.charAt(Math.floor(Math.random() * items.length));' }
        ]
    },

    // _cleanProxySettings 中 isFalse 被错误赋值为 hasChanged
    {
        desc: '_cleanProxySettings: hasChanged -> isFalse',
        fixes: [
            { old: 'hasChanged = true;',
              new: 'isFalse = true;' }
        ]
    }
];

let totalFixed = 0;

bugFixes.forEach(group => {
    console.log(`📝 ${group.desc}`);
    group.fixes.forEach(fix => {
        if (code.includes(fix.old)) {
            code = code.replace(fix.old, fix.new);
            totalFixed++;
            console.log(`   ✓ 已修复`);
        } else {
            // 可能已经修复或者精确匹配失败
        }
    });
});

console.log(`\n总计修复 ${totalFixed} 处`);

fs.writeFileSync(inputPath, code);

// 验证语法
const babel = require('@babel/core');
try {
    babel.parseSync(code, { sourceType: 'script' });
    console.log('✅ 语法正确');
} catch (e) {
    console.error('❌ 语法错误:', e.message);
    console.error('位置:', e.loc);
}
