"use strict";
/**
 * Generic CLI session management
 * Manages CLI tool sessions (Claude, Codex, Gemini) within tmux
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.isSessionRunning = isSessionRunning;
exports.captureSessionOutput = captureSessionOutput;
exports.getSessionName = getSessionName;
const tmux_1 = require("./tmux");
const manager_1 = require("./cli-tools/manager");
const logger_1 = require("./logger");
const logger = (0, logger_1.createLogger)('cli-session');
/**
 * Check if CLI tool session is running
 *
 * @param worktreeId - Worktree ID
 * @param cliToolId - CLI tool ID (claude, codex, gemini)
 * @returns True if session exists and is running
 */
async function isSessionRunning(worktreeId, cliToolId) {
    const manager = manager_1.CLIToolManager.getInstance();
    const cliTool = manager.getTool(cliToolId);
    const sessionName = cliTool.getSessionName(worktreeId);
    return await (0, tmux_1.hasSession)(sessionName);
}
/**
 * Capture CLI session output
 *
 * @param worktreeId - Worktree ID
 * @param cliToolId - CLI tool ID (claude, codex, gemini)
 * @param lines - Number of lines to capture (default: 1000)
 * @returns Captured output
 */
async function captureSessionOutput(worktreeId, cliToolId, lines = 1000) {
    const log = logger.withContext({ worktreeId, cliToolId });
    log.debug('captureSessionOutput:start', { requestedLines: lines });
    const manager = manager_1.CLIToolManager.getInstance();
    const cliTool = manager.getTool(cliToolId);
    const sessionName = cliTool.getSessionName(worktreeId);
    // Check if session exists
    const exists = await (0, tmux_1.hasSession)(sessionName);
    if (!exists) {
        log.debug('captureSessionOutput:sessionNotFound', { sessionName });
        throw new Error(`${cliTool.name} session ${sessionName} does not exist`);
    }
    try {
        const output = await (0, tmux_1.capturePane)(sessionName, { startLine: -lines });
        const actualLines = output.split('\n').length;
        log.debug('captureSessionOutput:success', {
            actualLines,
            lastFewLines: output.split('\n').slice(-3).join(' | '),
        });
        return output;
    }
    catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        log.error('captureSessionOutput:failed', { error: errorMessage });
        throw new Error(`Failed to capture ${cliTool.name} output: ${errorMessage}`);
    }
}
/**
 * Get session name for a CLI tool and worktree
 *
 * @param worktreeId - Worktree ID
 * @param cliToolId - CLI tool ID
 * @returns Session name
 */
function getSessionName(worktreeId, cliToolId) {
    const manager = manager_1.CLIToolManager.getInstance();
    const cliTool = manager.getTool(cliToolId);
    return cliTool.getSessionName(worktreeId);
}
