"use strict";
/**
 * Auto-Repair Module - Fix common issues automatically
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runAutoRepair = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ui_1 = require("../../utils/ui");
const cliproxy_1 = require("../../cliproxy");
const port_utils_1 = require("../../utils/port-utils");
const platform_commands_1 = require("../../utils/platform-commands");
const types_1 = require("../checks/types");
const image_analysis_check_1 = require("../checks/image-analysis-check");
const config_loader_facade_1 = require("../../config/config-loader-facade");
const ora = (0, types_1.createSpinner)();
/**
 * Fix detected issues automatically
 * Fixes:
 * 1. Zombie CLIProxy processes blocking ports
 * 2. Outdated CLIProxy config files
 * 3. Shared symlinks broken by Claude CLI's atomic writes
 * 4. OAuth callback ports blocked by CLIProxy
 */
async function runAutoRepair() {
    console.log('');
    console.log((0, ui_1.header)('AUTO-FIX MODE'));
    console.log('');
    console.log((0, ui_1.info)(`Platform: ${(0, platform_commands_1.getPlatformName)()}`));
    console.log('');
    let fixed = 0;
    // Fix 1: Kill zombie CLIProxy processes
    const zombieSpinner = ora('Checking for zombie CLIProxy processes').start();
    try {
        // Check main CLIProxy port
        const portProcess = await (0, port_utils_1.getPortProcess)(cliproxy_1.CLIPROXY_DEFAULT_PORT);
        if (portProcess && (0, port_utils_1.isCLIProxyProcess)(portProcess)) {
            zombieSpinner.text = 'Killing zombie CLIProxy process...';
            const killed = (0, platform_commands_1.killProcessOnPort)(cliproxy_1.CLIPROXY_DEFAULT_PORT, true);
            if (killed) {
                zombieSpinner.succeed(`${(0, ui_1.ok)('Fixed')} Killed zombie CLIProxy on port ${cliproxy_1.CLIPROXY_DEFAULT_PORT}`);
                fixed++;
            }
            else {
                zombieSpinner.warn(`${(0, ui_1.warn)('Partial')} CLIProxy detected but could not kill`);
            }
        }
        else if (portProcess) {
            zombieSpinner.info(`${(0, ui_1.info)('Info')} Port ${cliproxy_1.CLIPROXY_DEFAULT_PORT} used by ${portProcess.processName} (not CLIProxy)`);
        }
        else {
            zombieSpinner.succeed(`${(0, ui_1.ok)('OK')} No zombie CLIProxy processes found`);
        }
    }
    catch (err) {
        zombieSpinner.fail(`${(0, ui_1.fail)('Error')} Could not check processes: ${err.message}`);
    }
    // Fix 2: Kill CLIProxy processes on OAuth callback ports
    const oauthPorts = [8085, 1455, 51121]; // Gemini, Codex, Agy
    for (const port of oauthPorts) {
        const oauthSpinner = ora(`Checking OAuth port ${port}`).start();
        try {
            const portProcess = await (0, port_utils_1.getPortProcess)(port);
            if (portProcess && (0, port_utils_1.isCLIProxyProcess)(portProcess)) {
                oauthSpinner.text = `Freeing OAuth port ${port}...`;
                const killed = (0, platform_commands_1.killProcessOnPort)(port, true);
                if (killed) {
                    oauthSpinner.succeed(`${(0, ui_1.ok)('Fixed')} Freed OAuth port ${port}`);
                    fixed++;
                }
                else {
                    oauthSpinner.warn(`${(0, ui_1.warn)('Partial')} CLIProxy on port ${port} but could not kill`);
                }
            }
            else if (portProcess) {
                oauthSpinner.info(`${(0, ui_1.info)('Info')} Port ${port} used by ${portProcess.processName} - please close manually`);
            }
            else {
                oauthSpinner.succeed(`${(0, ui_1.ok)('OK')} OAuth port ${port} is free`);
            }
        }
        catch (_err) {
            oauthSpinner.succeed(`${(0, ui_1.ok)('OK')} OAuth port ${port} check passed`);
        }
    }
    // Fix 3: Regenerate outdated CLIProxy config
    const configSpinner = ora('Checking CLIProxy config version').start();
    try {
        if ((0, cliproxy_1.configNeedsRegeneration)()) {
            configSpinner.text = 'Upgrading CLIProxy config...';
            (0, cliproxy_1.regenerateConfig)();
            configSpinner.succeed(`${(0, ui_1.ok)('Fixed')} Upgraded CLIProxy config to v${cliproxy_1.CLIPROXY_CONFIG_VERSION}`);
            fixed++;
        }
        else {
            configSpinner.succeed(`${(0, ui_1.ok)('OK')} CLIProxy config is up to date`);
        }
    }
    catch (err) {
        configSpinner.fail(`${(0, ui_1.fail)('Error')} Could not upgrade config: ${err.message}`);
    }
    // Fix 4: Fix shared symlinks (settings.json broken by Claude CLI toggle thinking, etc.)
    const symlinkSpinner = ora('Checking shared settings.json symlink').start();
    const sharedSettings = path.join((0, config_loader_facade_1.getCcsDir)(), 'shared', 'settings.json');
    try {
        if (fs.existsSync(sharedSettings)) {
            const stats = fs.lstatSync(sharedSettings);
            if (!stats.isSymbolicLink()) {
                symlinkSpinner.text = 'Restoring shared settings.json symlink...';
                const SharedManagerModule = await Promise.resolve().then(() => __importStar(require('../shared-manager')));
                const SharedManager = SharedManagerModule.default;
                const sharedManager = new SharedManager();
                sharedManager.ensureSharedDirectories();
                symlinkSpinner.succeed(`${(0, ui_1.ok)('Fixed')} Restored shared settings.json symlink`);
                fixed++;
            }
            else {
                symlinkSpinner.succeed(`${(0, ui_1.ok)('OK')} Shared settings.json symlink is valid`);
            }
        }
        else {
            symlinkSpinner.succeed(`${(0, ui_1.ok)('OK')} Shared settings.json not yet created`);
        }
    }
    catch (err) {
        symlinkSpinner.fail(`${(0, ui_1.fail)('Error')} Could not fix symlink: ${err.message}`);
    }
    // Fix 5: Image analysis config validation
    const imageSpinner = ora('Checking image analysis config').start();
    try {
        const imageFixed = await (0, image_analysis_check_1.fixImageAnalysisConfig)();
        if (imageFixed) {
            imageSpinner.succeed(`${(0, ui_1.ok)('Fixed')} Repaired image analysis configuration`);
            fixed++;
        }
        else {
            imageSpinner.succeed(`${(0, ui_1.ok)('OK')} Image analysis config is valid`);
        }
    }
    catch (err) {
        imageSpinner.fail(`${(0, ui_1.fail)('Error')} Could not fix image config: ${err.message}`);
    }
    // Summary
    console.log('');
    if (fixed > 0) {
        console.log((0, ui_1.ok)(`Auto-fix complete: ${fixed} issue(s) resolved`));
        console.log('');
        console.log((0, ui_1.info)('Try your command again. If issues persist, run:'));
        console.log(`  ${(0, ui_1.color)('ccs doctor', 'command')}  - for full diagnostics`);
    }
    else {
        console.log((0, ui_1.ok)('No issues found that needed fixing'));
        console.log('');
        console.log((0, ui_1.info)('If you still have issues:'));
        console.log(`  1. Run ${(0, ui_1.color)('ccs doctor', 'command')} for diagnostics`);
        console.log(`  2. Try ${(0, ui_1.color)('ccs <provider> --auth --verbose', 'command')} for detailed logs`);
        console.log(`  3. Restart your terminal/computer`);
    }
    console.log('');
}
exports.runAutoRepair = runAutoRepair;
//# sourceMappingURL=auto-repair.js.map