"use strict";
/**
 * Session Bridge - Integration with session tracking and proxy detection
 *
 * Handles:
 * - Session registration and unregistration
 * - Proxy detection and version checking
 * - Orphaned proxy reclamation
 * - Startup lock coordination
 */
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.setupCleanupHandlers = exports.registerProxySession = exports.checkOrJoinProxy = void 0;
const ui_1 = require("../../utils/ui");
const binary_manager_1 = require("../binary-manager");
const session_tracker_1 = require("../session-tracker");
const proxy_detector_1 = require("../proxy/proxy-detector");
const startup_lock_1 = require("../services/startup-lock");
const platform_commands_1 = require("../../utils/platform-commands");
const quota_manager_1 = require("../quota/quota-manager");
/**
 * Check for existing proxy and handle version mismatch, or determine if new spawn needed
 */
async function checkOrJoinProxy(port, timeout, verbose) {
    const log = (msg) => {
        if (verbose) {
            console.error(`[cliproxy] ${msg}`);
        }
    };
    // Cleanup orphaned sessions before detection
    (0, session_tracker_1.cleanupOrphanedSessions)(port);
    let sessionId;
    let shouldSpawn = false;
    // Use startup lock to coordinate with other CCS processes
    await (0, startup_lock_1.withStartupLock)(async () => {
        // Detect running proxy using multiple methods (HTTP, session-lock, port-process)
        let proxyStatus = await (0, proxy_detector_1.detectRunningProxy)(port);
        log(`Proxy detection: ${JSON.stringify(proxyStatus)}`);
        // Check for version mismatch - restart proxy if installed version differs from running
        if (proxyStatus.running && proxyStatus.verified && proxyStatus.version) {
            const installedVersion = (0, binary_manager_1.getInstalledCliproxyVersion)();
            if (installedVersion !== proxyStatus.version) {
                console.log((0, ui_1.warn)(`Version mismatch: running v${proxyStatus.version}, installed v${installedVersion}. Restarting proxy...`));
                log(`Stopping outdated proxy (PID: ${proxyStatus.pid ?? 'unknown'})...`);
                const stopResult = await (0, session_tracker_1.stopProxy)(port);
                if (stopResult.stopped) {
                    log(`Stopped outdated proxy successfully`);
                }
                else {
                    log(`Stop proxy result: ${stopResult.error ?? 'unknown error'}`);
                }
                // Wait for port to be released
                await new Promise((r) => setTimeout(r, 500));
                // Re-detect proxy status (should now be not running)
                proxyStatus = await (0, proxy_detector_1.detectRunningProxy)(port);
                log(`Re-detection after version mismatch restart: ${JSON.stringify(proxyStatus)}`);
            }
        }
        if (proxyStatus.running && proxyStatus.verified) {
            // Healthy proxy found - join it
            if (proxyStatus.pid) {
                sessionId = (0, proxy_detector_1.reclaimOrphanedProxy)(port, proxyStatus.pid, verbose) ?? undefined;
            }
            if (sessionId) {
                console.log((0, ui_1.info)(`Joined existing CLIProxy on port ${port} (${proxyStatus.method})`));
            }
            else {
                // Failed to register session - proxy is running but we can't track it
                console.log((0, ui_1.info)(`Using existing CLIProxy on port ${port} (session tracking unavailable)`));
                log(`PID=${proxyStatus.pid ?? 'unknown'}, session registration skipped`);
            }
            return; // Exit lock early, skip spawning
        }
        if (proxyStatus.running && !proxyStatus.verified) {
            // Proxy detected but not ready yet (another process is starting it)
            log(`Proxy starting up (detected via ${proxyStatus.method}), waiting...`);
            const becameHealthy = await (0, proxy_detector_1.waitForProxyHealthy)(port, timeout);
            if (becameHealthy) {
                if (proxyStatus.pid) {
                    sessionId = (0, proxy_detector_1.reclaimOrphanedProxy)(port, proxyStatus.pid, verbose) ?? undefined;
                }
                console.log((0, ui_1.info)(`Joined CLIProxy after startup wait`));
                return; // Exit lock early
            }
            // Proxy didn't become healthy - kill and respawn
            if (proxyStatus.pid) {
                log(`Proxy PID ${proxyStatus.pid} not responding, killing...`);
                (0, platform_commands_1.killProcessOnPort)(port, verbose);
                await new Promise((r) => setTimeout(r, 500));
            }
        }
        if (proxyStatus.blocked && proxyStatus.blocker) {
            // Port blocked by non-CLIProxy process
            // Last resort: try HTTP health check (handles Windows PID-XXXXX case)
            const isActuallyOurs = await (0, proxy_detector_1.waitForProxyHealthy)(port, 1000);
            if (isActuallyOurs) {
                sessionId = (0, proxy_detector_1.reclaimOrphanedProxy)(port, proxyStatus.blocker.pid, verbose) ?? undefined;
                console.log((0, ui_1.info)(`Reclaimed CLIProxy with unrecognized process name`));
                return;
            }
            // Truly blocked by another application
            const { getPortCheckCommand } = await Promise.resolve().then(() => __importStar(require('../../utils/platform-commands')));
            console.error('');
            console.error((0, ui_1.warn)(`Port ${port} is blocked by ${proxyStatus.blocker.processName} (PID ${proxyStatus.blocker.pid})`));
            console.error('');
            console.error('To fix this, close the blocking application or run:');
            console.error(`  ${getPortCheckCommand(port)}`);
            console.error('');
            throw new Error(`Port ${port} is in use by another application`);
        }
        // No proxy found - need to spawn
        shouldSpawn = true;
    });
    return { sessionId, shouldSpawn };
}
exports.checkOrJoinProxy = checkOrJoinProxy;
/**
 * Register a new proxy session after spawning
 */
function registerProxySession(port, pid, backend, verbose) {
    const installedVersion = (0, binary_manager_1.getInstalledCliproxyVersion)();
    const sessionId = (0, session_tracker_1.registerSession)(port, pid, installedVersion, backend);
    if (verbose) {
        console.error(`[cliproxy] Registered session ${sessionId} with new proxy (PID ${pid}, version ${installedVersion})`);
    }
    return sessionId;
}
exports.registerProxySession = registerProxySession;
/**
 * Setup cleanup handlers for session unregistration
 */
function setupCleanupHandlers(claude, sessionId, sessionPort, codexReasoningProxy, toolSanitizationProxy, httpsTunnel, verbose) {
    const log = (msg) => {
        if (verbose) {
            console.error(`[cliproxy] ${msg}`);
        }
    };
    let resourcesStopped = false;
    const stopResource = (resource) => {
        if (resource && typeof resource === 'object' && 'stop' in resource) {
            resource.stop();
        }
    };
    const stopSessionResources = () => {
        if (resourcesStopped)
            return;
        resourcesStopped = true;
        (0, quota_manager_1.stopQuotaMonitor)();
        stopResource(codexReasoningProxy);
        stopResource(toolSanitizationProxy);
        stopResource(httpsTunnel);
        if (sessionId) {
            (0, session_tracker_1.unregisterSession)(sessionId, sessionPort);
            log(`Session ${sessionId} unregistered, proxy persists for other sessions or future use`);
        }
    };
    const cleanup = () => {
        log('Parent signal received, cleaning up');
        stopSessionResources();
        claude.kill('SIGTERM');
    };
    claude.on('exit', (code, signal) => {
        log(`Claude exited: code=${code}, signal=${signal}`);
        stopSessionResources();
        if (signal) {
            process.kill(process.pid, signal);
        }
        else {
            process.exit(code || 0);
        }
    });
    claude.on('error', (error) => {
        console.error(require('../../utils/ui').fail(`Claude CLI error: ${error}`));
        stopSessionResources();
        process.exit(1);
    });
    process.once('SIGTERM', cleanup);
    process.once('SIGINT', cleanup);
}
exports.setupCleanupHandlers = setupCleanupHandlers;
//# sourceMappingURL=session-bridge.js.map