"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.restartDashboardCliproxy = void 0;
const port_manager_1 = require("../../cliproxy/config/port-manager");
const service_manager_1 = require("../../cliproxy/service-manager");
const proxy_detector_1 = require("../../cliproxy/proxy/proxy-detector");
const session_tracker_1 = require("../../cliproxy/session-tracker");
const supervisord_lifecycle_1 = require("../../docker/supervisord-lifecycle");
const RESTART_SETTLE_MS = 500;
const SUPERVISOR_HEALTH_TIMEOUT_MS = 10000;
function delay(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}
function startResultToRestartResult(startResult) {
    if (startResult.started || startResult.alreadyRunning) {
        return { success: true, port: startResult.port };
    }
    return { success: false, error: startResult.error || 'Failed to start proxy' };
}
async function restartDashboardCliproxy(deps = {}) {
    const resolveLifecyclePortFn = deps.resolveLifecyclePortFn ?? port_manager_1.resolveLifecyclePort;
    const isRunningUnderSupervisordFn = deps.isRunningUnderSupervisordFn ?? supervisord_lifecycle_1.isRunningUnderSupervisord;
    const restartCliproxyViaSupervisordFn = deps.restartCliproxyViaSupervisordFn ?? supervisord_lifecycle_1.restartCliproxyViaSupervisord;
    const waitForProxyHealthyFn = deps.waitForProxyHealthyFn ?? proxy_detector_1.waitForProxyHealthy;
    const stopProxyFn = deps.stopProxyFn ?? session_tracker_1.stopProxy;
    const ensureCliproxyServiceFn = deps.ensureCliproxyServiceFn ?? service_manager_1.ensureCliproxyService;
    const delayFn = deps.delayFn ?? delay;
    const port = resolveLifecyclePortFn();
    if (isRunningUnderSupervisordFn()) {
        const supervisorResult = restartCliproxyViaSupervisordFn();
        if (!supervisorResult.success) {
            return supervisorResult;
        }
        const healthy = await waitForProxyHealthyFn(port, SUPERVISOR_HEALTH_TIMEOUT_MS);
        if (!healthy) {
            return {
                success: false,
                error: 'CLIProxy did not become healthy after supervisor restart',
            };
        }
        return { success: true, port: supervisorResult.port ?? port };
    }
    await stopProxyFn(port);
    await delayFn(RESTART_SETTLE_MS);
    const startResult = await ensureCliproxyServiceFn(port);
    return startResultToRestartResult(startResult);
}
exports.restartDashboardCliproxy = restartDashboardCliproxy;
//# sourceMappingURL=cliproxy-dashboard-restart-service.js.map