"use strict";
/**
 * Lifecycle Manager - Spawn/Kill/Poll operations for CLIProxy
 *
 * Handles:
 * - Spawning CLIProxyAPI binary
 * - Waiting for proxy readiness via TCP polling
 * - Killing proxy processes
 */
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.findAvailablePort = exports.isPortAvailable = exports.waitForProxyReadyWithSpinner = exports.spawnProxy = exports.waitForProxyReady = void 0;
const child_process_1 = require("child_process");
const net = __importStar(require("net"));
const progress_indicator_1 = require("../../utils/progress-indicator");
const ui_1 = require("../../utils/ui");
const config_generator_1 = require("../config/config-generator");
const platform_commands_1 = require("../../utils/platform-commands");
/**
 * Wait for TCP port to become available
 * Uses polling since CLIProxyAPI doesn't emit PROXY_READY signal
 */
async function waitForProxyReady(port, timeout = 5000, pollInterval = 100) {
    const start = Date.now();
    while (Date.now() - start < timeout) {
        try {
            await new Promise((resolve, reject) => {
                const socket = net.createConnection({ port, host: '127.0.0.1' }, () => {
                    socket.destroy();
                    resolve();
                });
                socket.on('error', (err) => {
                    socket.destroy();
                    reject(err);
                });
                // Individual connection timeout
                socket.setTimeout(1000, () => {
                    socket.destroy();
                    reject(new Error('Connection timeout'));
                });
            });
            return; // Connection successful - proxy is ready
        }
        catch {
            // Connection failed, wait and retry
            await new Promise((r) => setTimeout(r, pollInterval));
        }
    }
    throw new Error(`CLIProxy not ready after ${timeout}ms on port ${port}`);
}
exports.waitForProxyReady = waitForProxyReady;
/**
 * Spawn CLIProxyAPI binary with given config
 */
function spawnProxy(binaryPath, configPath, verbose) {
    const log = (msg) => {
        if (verbose) {
            console.error(`[cliproxy] ${msg}`);
        }
    };
    const proxyArgs = ['--config', configPath];
    log(`Spawning: ${binaryPath} ${proxyArgs.join(' ')}`);
    const proxy = (0, child_process_1.spawn)(binaryPath, proxyArgs, {
        stdio: ['ignore', 'ignore', 'ignore'],
        detached: true,
        env: {
            ...process.env,
            WRITABLE_PATH: (0, config_generator_1.getCliproxyWritablePath)(),
        },
    });
    proxy.unref();
    proxy.on('error', (error) => {
        console.error((0, ui_1.fail)(`CLIProxy spawn error: ${error.message}`));
    });
    return proxy;
}
exports.spawnProxy = spawnProxy;
/**
 * Wait for proxy to be ready with progress indication
 */
async function waitForProxyReadyWithSpinner(port, timeout, pollInterval, backend, configPath) {
    const readySpinner = new progress_indicator_1.ProgressIndicator(`Waiting for CLIProxy on port ${port}`);
    readySpinner.start();
    try {
        await waitForProxyReady(port, timeout, pollInterval);
        readySpinner.succeed(`CLIProxy ready on port ${port}`);
    }
    catch (error) {
        const backendLabel = backend === 'plus' ? 'CLIProxy Plus' : 'CLIProxy';
        readySpinner.fail(`${backendLabel} startup failed`);
        const err = error;
        console.error('');
        console.error((0, ui_1.fail)(`${backendLabel} failed to start`));
        console.error('');
        console.error('Possible causes:');
        console.error(`  1. Port ${port} already in use`);
        console.error('  2. Binary crashed on startup');
        console.error('  3. Invalid configuration');
        console.error('');
        console.error('Troubleshooting:');
        console.error(`  - Check port: ${(0, platform_commands_1.getPortCheckCommand)(port)}`);
        console.error('  - Run with --verbose for detailed logs');
        console.error(`  - View config: ${(0, platform_commands_1.getCatCommand)(configPath)}`);
        console.error('  - Try: ccs doctor --fix');
        console.error('');
        throw new Error(`CLIProxy startup failed: ${err.message}`);
    }
}
exports.waitForProxyReadyWithSpinner = waitForProxyReadyWithSpinner;
/**
 * Check if a port is available
 */
async function isPortAvailable(port) {
    return new Promise((resolve) => {
        const server = net.createServer();
        server.once('error', () => {
            resolve(false);
        });
        server.once('listening', () => {
            server.close();
            resolve(true);
        });
        server.listen(port, '127.0.0.1');
    });
}
exports.isPortAvailable = isPortAvailable;
/**
 * Find an available port in range
 */
async function findAvailablePort(startPort, range = 10) {
    for (let port = startPort; port < startPort + range; port++) {
        if (await isPortAvailable(port)) {
            return port;
        }
    }
    throw new Error(`No available port found in range ${startPort}-${startPort + range - 1}`);
}
exports.findAvailablePort = findAvailablePort;
//# sourceMappingURL=lifecycle-manager.js.map