"use strict";
/**
 * CLIProxy Plus Health Checks - Binary, config, auth, and port status
 */
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.runCLIProxyChecks = exports.CLIProxyPortChecker = exports.CLIProxyAuthChecker = exports.CLIProxyConfigChecker = exports.CLIProxyBinaryChecker = void 0;
const fs = __importStar(require("fs"));
const ui_1 = require("../../utils/ui");
const cliproxy_1 = require("../../cliproxy");
const port_utils_1 = require("../../utils/port-utils");
const types_1 = require("./types");
const ora = (0, types_1.createSpinner)();
/**
 * Check CLIProxy Plus binary installation
 */
class CLIProxyBinaryChecker {
    constructor() {
        this.name = 'CLIProxy Plus Binary';
    }
    run(results) {
        const spinner = ora('Checking CLIProxy Plus binary').start();
        if ((0, cliproxy_1.isCLIProxyInstalled)()) {
            const binaryPath = (0, cliproxy_1.getCLIProxyPath)();
            const installedVersion = (0, cliproxy_1.getInstalledCliproxyVersion)();
            spinner.succeed();
            console.log(`  ${(0, ui_1.ok)('CLIProxy Plus'.padEnd(22))}  v${installedVersion}`);
            results.addCheck('CLIProxy Binary', 'success', undefined, undefined, {
                status: 'OK',
                info: `v${installedVersion} (${binaryPath})`,
            });
        }
        else {
            spinner.info();
            console.log(`  ${(0, ui_1.info)('CLIProxy Plus'.padEnd(22))}  Not installed (downloads on first use)`);
            results.addCheck('CLIProxy Binary', 'success', 'Not installed yet', 'Run: ccs gemini "test" (will download automatically)', { status: 'OK', info: 'Not installed (downloads on first use)' });
        }
    }
}
exports.CLIProxyBinaryChecker = CLIProxyBinaryChecker;
/**
 * Check CLIProxy config file
 */
class CLIProxyConfigChecker {
    constructor() {
        this.name = 'CLIProxy Config';
    }
    run(results) {
        const spinner = ora('Checking CLIProxy config').start();
        const configPath = (0, cliproxy_1.getCliproxyConfigPath)();
        if (fs.existsSync(configPath)) {
            // Check if config needs regeneration (version mismatch or missing features)
            if ((0, cliproxy_1.configNeedsRegeneration)()) {
                spinner.warn();
                console.log(`  ${(0, ui_1.warn)('CLIProxy Config'.padEnd(22))}  Outdated config, upgrading to v${cliproxy_1.CLIPROXY_CONFIG_VERSION}...`);
                // Regenerate config with new features
                (0, cliproxy_1.regenerateConfig)();
                console.log(`  ${(0, ui_1.ok)('CLIProxy Config'.padEnd(22))}  Upgraded to v${cliproxy_1.CLIPROXY_CONFIG_VERSION}`);
                results.addCheck('CLIProxy Config', 'success', undefined, undefined, {
                    status: 'OK',
                    info: `Upgraded to v${cliproxy_1.CLIPROXY_CONFIG_VERSION}`,
                });
            }
            else {
                spinner.succeed();
                console.log(`  ${(0, ui_1.ok)('CLIProxy Config'.padEnd(22))}  cliproxy/config.yaml (v${cliproxy_1.CLIPROXY_CONFIG_VERSION})`);
                results.addCheck('CLIProxy Config', 'success', undefined, undefined, {
                    status: 'OK',
                    info: `cliproxy/config.yaml (v${cliproxy_1.CLIPROXY_CONFIG_VERSION})`,
                });
            }
        }
        else {
            spinner.info();
            console.log(`  ${(0, ui_1.info)('CLIProxy Config'.padEnd(22))}  Not created (on first use)`);
            results.addCheck('CLIProxy Config', 'success', 'Not created yet', undefined, {
                status: 'OK',
                info: 'Generated on first use',
            });
        }
    }
}
exports.CLIProxyConfigChecker = CLIProxyConfigChecker;
/**
 * Check OAuth status for all providers
 */
class CLIProxyAuthChecker {
    constructor() {
        this.name = 'CLIProxy Auth';
    }
    run(results) {
        const authStatuses = (0, cliproxy_1.getAllAuthStatus)();
        for (const status of authStatuses) {
            const spinner = ora(`Checking ${status.provider} auth`).start();
            const providerName = status.provider.charAt(0).toUpperCase() + status.provider.slice(1);
            if (status.authenticated) {
                const lastAuth = status.lastAuth ? ` (${status.lastAuth.toLocaleDateString()})` : '';
                spinner.succeed();
                console.log(`  ${(0, ui_1.ok)(`${providerName} Auth`.padEnd(22))}  Authenticated${lastAuth}`);
                results.addCheck(`${providerName} Auth`, 'success', undefined, undefined, {
                    status: 'OK',
                    info: `Authenticated${lastAuth}`,
                });
            }
            else {
                spinner.info();
                console.log(`  ${(0, ui_1.info)(`${providerName} Auth`.padEnd(22))}  Not authenticated`);
                results.addCheck(`${providerName} Auth`, 'success', 'Not authenticated', `Run: ccs ${status.provider} --auth`, { status: 'OK', info: 'Not authenticated (run ccs <profile> to login)' });
            }
        }
    }
}
exports.CLIProxyAuthChecker = CLIProxyAuthChecker;
/**
 * Check CLIProxy port status
 */
class CLIProxyPortChecker {
    constructor() {
        this.name = 'CLIProxy Port';
    }
    async run(results) {
        const spinner = ora(`Checking port ${cliproxy_1.CLIPROXY_DEFAULT_PORT}`).start();
        const portProcess = await (0, port_utils_1.getPortProcess)(cliproxy_1.CLIPROXY_DEFAULT_PORT);
        if (!portProcess) {
            // Port is free
            spinner.info();
            console.log(`  ${(0, ui_1.info)('CLIProxy Port'.padEnd(22))}  ${cliproxy_1.CLIPROXY_DEFAULT_PORT} free (proxy not running)`);
            results.addCheck('CLIProxy Port', 'success', undefined, undefined, {
                status: 'OK',
                info: `Port ${cliproxy_1.CLIPROXY_DEFAULT_PORT} free`,
            });
        }
        else if ((0, port_utils_1.isCLIProxyProcess)(portProcess)) {
            // CLIProxy is running (expected)
            spinner.succeed();
            console.log(`  ${(0, ui_1.ok)('CLIProxy Port'.padEnd(22))}  CLIProxy running (PID ${portProcess.pid})`);
            results.addCheck('CLIProxy Port', 'success', undefined, undefined, {
                status: 'OK',
                info: `CLIProxy running (PID ${portProcess.pid})`,
            });
        }
        else {
            // Port conflict - different process
            spinner.warn();
            console.log(`  ${(0, ui_1.warn)('CLIProxy Port'.padEnd(22))}  ${cliproxy_1.CLIPROXY_DEFAULT_PORT} occupied by ${portProcess.processName}`);
            results.addCheck('CLIProxy Port', 'warning', `Port ${cliproxy_1.CLIPROXY_DEFAULT_PORT} occupied by ${portProcess.processName} (PID ${portProcess.pid})`, `Kill process: kill ${portProcess.pid} (or restart conflicting application)`, { status: 'WARN', info: `Occupied by ${portProcess.processName}` });
        }
    }
}
exports.CLIProxyPortChecker = CLIProxyPortChecker;
/**
 * Run all CLIProxy checks
 */
async function runCLIProxyChecks(results) {
    const binaryChecker = new CLIProxyBinaryChecker();
    const configChecker = new CLIProxyConfigChecker();
    const authChecker = new CLIProxyAuthChecker();
    const portChecker = new CLIProxyPortChecker();
    binaryChecker.run(results);
    configChecker.run(results);
    authChecker.run(results);
    await portChecker.run(results);
}
exports.runCLIProxyChecks = runCLIProxyChecks;
//# sourceMappingURL=cliproxy-check.js.map