/**
 * Handler for command_exec messages.
 *
 * Executes a shell command in the project directory, streaming
 * command_output events and sending a final command_exit event.
 */
import { ErrorCode } from "@pocketcoder/shared/constants";
import { getProject } from "../db/repositories/projects.js";
import { createCommandRun, updateCommandRun } from "../db/repositories/command-runs.js";
import { executeCommand } from "../services/command-runner.js";
import { logger } from "../utils/logger.js";
export async function handleCommandExec(message, send) {
    const msg = message;
    const { requestId, sessionId, payload } = msg;
    const { command } = payload;
    // Resolve project from sessionId (which is the projectId)
    const project = getProject(sessionId);
    if (!project) {
        send({
            type: "error",
            requestId,
            error: {
                code: ErrorCode.INVALID_REQUEST,
                message: `Project not found: ${sessionId}`,
            },
        });
        return;
    }
    // Track command in database
    try {
        createCommandRun(requestId, sessionId, command);
    }
    catch (err) {
        logger.warn(`Failed to create command run record: ${err instanceof Error ? err.message : String(err)}`);
    }
    logger.info(`Executing command in ${project.path}: ${command}`);
    // Execute command with streaming output
    const result = await executeCommand(requestId, sessionId, command, project.path, (output) => {
        const event = {
            type: "command_output",
            requestId,
            payload: {},
        };
        if (output.stdoutChunk) {
            event.payload.stdoutChunk = output.stdoutChunk;
        }
        if (output.stderrChunk) {
            event.payload.stderrChunk = output.stderrChunk;
        }
        send(event);
    });
    // Update database record
    try {
        updateCommandRun(requestId, result.exitCode ?? -1, result.outputPreview || null, result.truncated);
    }
    catch (err) {
        logger.warn(`Failed to update command run record: ${err instanceof Error ? err.message : String(err)}`);
    }
    // Send command_exit event
    const exitEvent = {
        type: "command_exit",
        requestId,
        payload: {
            exitCode: result.exitCode,
            durationMs: result.durationMs,
        },
    };
    if (result.signal) {
        exitEvent.payload.signal = result.signal;
    }
    send(exitEvent);
    logger.info(`Command completed: requestId=${requestId} exitCode=${result.exitCode} duration=${result.durationMs}ms truncated=${result.truncated}`);
}
//# sourceMappingURL=command-exec.js.map