/**
 * CLI entrypoint for kernel execution (PR 2).
 *
 * Thin wrapper — reads JSON request from --input, stdin, or --json, hands
 * it to kernel.run.step/verify/merge, prints the result. Every effect goes
 * through the same kernel service that MCP uses, so CLI and MCP are not
 * allowed to drift.
 */
import fs from 'node:fs';
import { configureKernelExecutionService, kernel } from '../kernel/index.js';
export async function runKernelExec(options) {
    const payload = await loadPayload(options);
    if (options.repoRoot) {
        configureKernelExecutionService({
            repoRoot: options.repoRoot,
            worktreeRoot: options.worktreeRoot,
        });
    }
    let result;
    try {
        switch (options.op) {
            case 'step':
                result = await kernel.run.step(payload);
                break;
            case 'verify':
                result = await kernel.run.verify(payload);
                break;
            case 'merge':
                result = await kernel.run.merge(payload);
                break;
            default:
                throw new Error(`unknown kernel op: ${String(options.op)}`);
        }
    }
    catch (err) {
        process.stderr.write(`kernel ${options.op} failed: ${err?.message ?? err}\n`);
        process.exit(1);
    }
    process.stdout.write(JSON.stringify(result, null, 2) + '\n');
}
async function loadPayload(options) {
    if (options.json)
        return JSON.parse(options.json);
    if (options.input)
        return JSON.parse(await fs.promises.readFile(options.input, 'utf8'));
    // Fall back to stdin.
    if (!process.stdin.isTTY) {
        const chunks = [];
        for await (const chunk of process.stdin) {
            chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
        }
        const buf = Buffer.concat(chunks).toString('utf8').trim();
        if (buf.length > 0)
            return JSON.parse(buf);
    }
    throw new Error('kernel exec requires --input <file>, --json <payload>, or stdin JSON');
}
