"use strict";
/**
 * Cursor Daemon Manager
 *
 * Manages the cursor daemon lifecycle (start/stop/status).
 * Uses CursorExecutor for OpenAI-compatible API proxy to Cursor backend.
 */
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.stopDaemon = exports.startDaemon = exports.getDaemonStatus = exports.isDaemonRunning = exports.removePidFile = exports.writePidToFile = exports.getPidFromFile = void 0;
const child_process_1 = require("child_process");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const http = __importStar(require("http"));
const cursor_daemon_pid_1 = require("./cursor-daemon-pid");
const daemon_process_ownership_1 = require("./daemon-process-ownership");
const logging_1 = require("../services/logging");
var cursor_daemon_pid_2 = require("./cursor-daemon-pid");
Object.defineProperty(exports, "getPidFromFile", { enumerable: true, get: function () { return cursor_daemon_pid_2.getPidFromFile; } });
Object.defineProperty(exports, "writePidToFile", { enumerable: true, get: function () { return cursor_daemon_pid_2.writePidToFile; } });
Object.defineProperty(exports, "removePidFile", { enumerable: true, get: function () { return cursor_daemon_pid_2.removePidFile; } });
const logger = (0, logging_1.createLogger)('cursor:daemon');
/**
 * Resolve daemon entrypoint candidates for current runtime.
 * - Dist runtime always uses JS artifact.
 * - Bun source runtime prefers TS, then falls back to JS.
 */
function getDaemonEntrypointCandidates() {
    const jsEntry = path.join(__dirname, 'cursor-daemon-entry.js');
    const tsEntry = path.join(__dirname, 'cursor-daemon-entry.ts');
    const isBunRuntime = process.execPath.toLowerCase().includes('bun');
    const runningFromDist = __filename.endsWith('.js');
    if (runningFromDist) {
        return [jsEntry];
    }
    if (isBunRuntime) {
        return [tsEntry, jsEntry];
    }
    return [jsEntry];
}
async function resolveDaemonEntrypoint() {
    for (const candidate of getDaemonEntrypointCandidates()) {
        try {
            await fs.promises.access(candidate, fs.constants.R_OK);
            return candidate;
        }
        catch {
            // Try next candidate
        }
    }
    return null;
}
/**
 * Check if cursor daemon is running on the specified port.
 * Uses 127.0.0.1 instead of localhost for more reliable local connections.
 */
async function isDaemonRunning(port) {
    return new Promise((resolve) => {
        const req = http.request({
            hostname: '127.0.0.1',
            port,
            path: '/health',
            method: 'GET',
            timeout: 3000,
        }, (res) => {
            let body = '';
            res.setEncoding('utf8');
            res.on('data', (chunk) => {
                body += chunk;
            });
            res.on('end', () => {
                if (res.statusCode !== 200) {
                    resolve(false);
                    return;
                }
                try {
                    const payload = JSON.parse(body);
                    resolve(payload.service === 'cursor-daemon');
                }
                catch {
                    resolve(false);
                }
            });
        });
        req.on('error', () => {
            resolve(false);
        });
        req.on('timeout', () => {
            req.destroy();
            resolve(false);
        });
        req.end();
    });
}
exports.isDaemonRunning = isDaemonRunning;
/**
 * Get daemon status.
 */
async function getDaemonStatus(port) {
    const running = await isDaemonRunning(port);
    const pid = (0, cursor_daemon_pid_1.getPidFromFile)();
    return {
        running,
        port,
        pid: running ? (pid ?? undefined) : undefined,
    };
}
exports.getDaemonStatus = getDaemonStatus;
/**
 * Start the cursor daemon.
 *
 * @param config Cursor configuration
 * @returns Promise that resolves when daemon is ready
 */
async function startDaemon(config) {
    // Check if already running
    if (await isDaemonRunning(config.port)) {
        logger.stage('dispatch', 'cursor.daemon.already_running', 'Cursor daemon already running', {
            provider: 'cursor',
            port: config.port,
        });
        return { success: true, pid: (0, cursor_daemon_pid_1.getPidFromFile)() ?? undefined };
    }
    // Validate port before interpolation (prevents injection)
    if (!Number.isInteger(config.port) || config.port < 1 || config.port > 65535) {
        return { success: false, error: `Invalid port: ${config.port}` };
    }
    const daemonEntry = await resolveDaemonEntrypoint();
    if (!daemonEntry) {
        return {
            success: false,
            error: 'Cursor daemon entrypoint not found. Run `bun run build` and retry.',
        };
    }
    const startedAt = Date.now();
    logger.stage('dispatch', 'cursor.daemon.spawn', 'Spawning Cursor daemon', {
        provider: 'cursor',
        port: config.port,
        ghostMode: config.ghost_mode !== false,
    });
    return new Promise((resolve) => {
        let proc;
        let resolved = false;
        const safeResolve = (result) => {
            if (resolved)
                return;
            resolved = true;
            if (checkTimeout)
                clearTimeout(checkTimeout);
            if (!result.success) {
                (0, cursor_daemon_pid_1.removePidFile)();
                logger.stage('cleanup', 'cursor.daemon.start_failed', 'Cursor daemon failed to start', { provider: 'cursor', port: config.port }, {
                    level: 'error',
                    latencyMs: Date.now() - startedAt,
                    error: result.error
                        ? { name: 'CursorDaemonStartError', message: result.error }
                        : undefined,
                });
            }
            else {
                logger.stage('upstream', 'cursor.daemon.ready', 'Cursor daemon is ready', { provider: 'cursor', port: config.port, pid: result.pid }, { latencyMs: Date.now() - startedAt });
            }
            resolve(result);
        };
        let checkTimeout = null;
        try {
            const args = [
                daemonEntry,
                '--port',
                String(config.port),
                '--ghost-mode',
                String(config.ghost_mode !== false),
                '--ccs-daemon',
            ];
            proc = (0, child_process_1.spawn)(process.execPath, args, {
                stdio: 'ignore',
                detached: true,
            });
            // Unref so parent can exit
            proc.unref();
            if (proc.pid) {
                (0, cursor_daemon_pid_1.writePidToFile)(proc.pid);
            }
            // Wait for daemon to be ready (poll for up to 30 seconds)
            let attempts = 0;
            const maxAttempts = 30;
            const pollHealth = async () => {
                attempts++;
                if (await isDaemonRunning(config.port)) {
                    safeResolve({ success: true, pid: proc.pid });
                }
                else if (attempts >= maxAttempts) {
                    // Kill orphaned process
                    if (proc.pid) {
                        try {
                            process.kill(proc.pid, 'SIGTERM');
                        }
                        catch {
                            /* already dead */
                        }
                    }
                    safeResolve({
                        success: false,
                        error: 'Daemon did not start within 30 seconds',
                    });
                }
                else {
                    checkTimeout = setTimeout(pollHealth, 1000);
                }
            };
            checkTimeout = setTimeout(pollHealth, 1000);
            proc.on('error', (err) => {
                safeResolve({
                    success: false,
                    error: `Failed to start daemon: ${err.message}`,
                });
            });
            proc.on('exit', (code, signal) => {
                if (code === null) {
                    safeResolve({
                        success: false,
                        error: `Daemon process was killed by signal ${signal}`,
                    });
                }
                else if (code === 0) {
                    safeResolve({
                        success: false,
                        error: 'Daemon process exited unexpectedly with code 0',
                    });
                }
                else {
                    safeResolve({
                        success: false,
                        error: `Daemon process exited with code ${code}`,
                    });
                }
            });
        }
        catch (err) {
            safeResolve({
                success: false,
                error: `Failed to spawn daemon: ${err.message}`,
            });
        }
    });
}
exports.startDaemon = startDaemon;
/**
 * Stop the cursor daemon.
 */
async function stopDaemon() {
    const pid = (0, cursor_daemon_pid_1.getPidFromFile)();
    if (!pid) {
        // No PID file — daemon is not running or was already stopped
        return { success: true };
    }
    try {
        const ownership = (0, daemon_process_ownership_1.verifyDaemonOwnership)(pid);
        if (ownership === 'not-running') {
            (0, cursor_daemon_pid_1.removePidFile)();
            return { success: true };
        }
        if (ownership === 'not-owned') {
            // PID was reused by an unrelated process.
            (0, cursor_daemon_pid_1.removePidFile)();
            return { success: true };
        }
        if (ownership === 'unknown') {
            return {
                success: false,
                error: `Refusing to stop PID ${pid}: unable to verify daemon ownership`,
            };
        }
        // Send SIGTERM to the process
        logger.stage('cleanup', 'cursor.daemon.stop', 'Sending SIGTERM to Cursor daemon', {
            provider: 'cursor',
            pid,
        });
        process.kill(pid, 'SIGTERM');
        // Wait for process to exit (up to 5 seconds)
        let attempts = 0;
        while (attempts < 10) {
            await new Promise((resolve) => setTimeout(resolve, 500));
            try {
                // Check if process still exists (kill(pid, 0) throws if not)
                process.kill(pid, 0);
                attempts++;
            }
            catch {
                // Process no longer exists
                break;
            }
        }
        // Escalate to SIGKILL only if SIGTERM wait loop exhausted
        if (attempts >= 10) {
            try {
                process.kill(pid, 'SIGKILL');
            }
            catch {
                // Already dead — good
            }
        }
        (0, cursor_daemon_pid_1.removePidFile)();
        return { success: true };
    }
    catch (err) {
        const error = err;
        if (error.code === 'ESRCH') {
            // Process doesn't exist
            (0, cursor_daemon_pid_1.removePidFile)();
            return { success: true };
        }
        return {
            success: false,
            error: `Failed to stop daemon: ${error.message}`,
        };
    }
}
exports.stopDaemon = stopDaemon;
//# sourceMappingURL=cursor-daemon.js.map