"use strict";
/**
 * CLIProxy Lifecycle Management
 *
 * Handles:
 * - ccs cliproxy start
 * - ccs cliproxy restart
 * - ccs cliproxy status
 * - ccs cliproxy stop
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleStop = exports.handleProxyStatus = exports.handleRestart = exports.handleStart = void 0;
const ui_1 = require("../../utils/ui");
const services_1 = require("../../cliproxy/services");
const proxy_detector_1 = require("../../cliproxy/proxy/proxy-detector");
const port_manager_1 = require("../../cliproxy/config/port-manager");
async function handleStart(verbose = false) {
    await (0, ui_1.initUI)();
    console.log((0, ui_1.header)('Start CLIProxy'));
    console.log('');
    const port = (0, port_manager_1.resolveLifecyclePort)();
    const result = await (0, services_1.startProxy)(port, verbose);
    if (result.started) {
        if (result.alreadyRunning) {
            console.log((0, ui_1.info)(`CLIProxy already running on port ${result.port}`));
            if (result.configRegenerated) {
                console.log((0, ui_1.warn)('Config updated - restart CLIProxy to apply changes'));
            }
        }
        else {
            console.log((0, ui_1.ok)(`CLIProxy started on port ${result.port}`));
        }
        console.log((0, ui_1.dim)('To stop: ccs cliproxy stop'));
    }
    else {
        console.log((0, ui_1.warn)(result.error || 'Failed to start CLIProxy'));
    }
    console.log('');
}
exports.handleStart = handleStart;
async function handleRestart(verbose = false) {
    await (0, ui_1.initUI)();
    console.log((0, ui_1.header)('Restart CLIProxy'));
    console.log('');
    const port = (0, port_manager_1.resolveLifecyclePort)();
    const stopResult = await (0, services_1.stopProxy)(port);
    if (stopResult.stopped) {
        console.log((0, ui_1.ok)(`CLIProxy stopped (PID ${stopResult.pid})`));
    }
    else if (stopResult.error === 'No active CLIProxy session found') {
        console.log((0, ui_1.info)('No active CLIProxy session found, starting a new instance'));
    }
    else {
        console.log((0, ui_1.warn)(stopResult.error || 'Failed to stop existing CLIProxy'));
        console.log((0, ui_1.info)('Attempting to start a fresh instance...'));
    }
    const startResult = await (0, services_1.startProxy)(port, verbose);
    if (startResult.started) {
        if (startResult.alreadyRunning) {
            console.log((0, ui_1.info)(`CLIProxy already running on port ${startResult.port}`));
        }
        else {
            console.log((0, ui_1.ok)(`CLIProxy started on port ${startResult.port}`));
        }
    }
    else {
        console.log((0, ui_1.warn)(startResult.error || 'Failed to restart CLIProxy'));
    }
    console.log('');
}
exports.handleRestart = handleRestart;
async function handleProxyStatus() {
    await (0, ui_1.initUI)();
    console.log((0, ui_1.header)('CLIProxy Status'));
    console.log('');
    const port = (0, port_manager_1.resolveLifecyclePort)();
    const status = (0, services_1.getProxyStatus)(port);
    if (status.running) {
        console.log(`  Status:     ${(0, ui_1.color)('Running', 'success')}`);
        console.log(`  PID:        ${status.pid}`);
        console.log(`  Port:       ${status.port}`);
        console.log(`  Sessions:   ${status.sessionCount || 0} active`);
        if (status.startedAt) {
            console.log(`  Started:    ${new Date(status.startedAt).toLocaleString()}`);
        }
        console.log('');
        console.log((0, ui_1.dim)('To stop: ccs cliproxy stop'));
    }
    else {
        // Fallback: detect untracked/orphaned proxy process (e.g. detached session without lock file).
        const detected = await (0, proxy_detector_1.detectRunningProxy)(port);
        if (detected.running && detected.verified) {
            console.log(`  Status:     ${(0, ui_1.color)('Running', 'success')}`);
            console.log(`  PID:        ${detected.pid ?? 'unknown'}`);
            console.log(`  Port:       ${port}`);
            console.log(`  Sessions:   ${detected.sessionCount || 0} active`);
            if (!detected.sessionCount) {
                console.log((0, ui_1.dim)('  Note: Detected running proxy without local session lock'));
            }
            console.log('');
            console.log((0, ui_1.dim)('To stop: ccs cliproxy stop'));
        }
        else {
            console.log(`  Status:     ${(0, ui_1.color)('Not running', 'warning')}`);
            console.log('');
            console.log((0, ui_1.dim)('CLIProxy starts automatically when you run ccs gemini, codex, etc.'));
        }
    }
    console.log('');
}
exports.handleProxyStatus = handleProxyStatus;
async function handleStop() {
    await (0, ui_1.initUI)();
    console.log((0, ui_1.header)('Stop CLIProxy'));
    console.log('');
    const port = (0, port_manager_1.resolveLifecyclePort)();
    const result = await (0, services_1.stopProxy)(port);
    if (result.stopped) {
        console.log((0, ui_1.ok)(`CLIProxy stopped (PID ${result.pid})`));
        if (result.sessionCount && result.sessionCount > 0) {
            console.log((0, ui_1.info)(`${result.sessionCount} active session(s) were disconnected`));
        }
    }
    else {
        console.log((0, ui_1.warn)(result.error || 'Failed to stop CLIProxy'));
    }
    console.log('');
}
exports.handleStop = handleStop;
//# sourceMappingURL=proxy-lifecycle-subcommand.js.map