/**
 * Phase C8 (olam-dogfood-vision): `olam lanes <subcommand>` — operator-
 * facing CRUD for claude-lane-* tmux sessions in a running world.
 *
 * Subcommands:
 *   list <world>                          — GET /lanes
 *   create <world> --name <n> --task <t>  — POST /lanes/create
 *   destroy <world> <name>                — DELETE /lanes/<name>
 *   dispatch <world> <name> <prompt>      — POST /lanes/<name>/dispatch
 *
 * Goes through host-cp's `/api/world/<id>/*` proxy (Bearer-auth) so the
 * operator never handles the per-world CP's CONTAINER_SECRET directly.
 * The host-cp proxy injects X-Olam-Secret server-side per the
 * established Phase F-2-D proxy contract.
 */
import { callHostCpProxy } from './host-cp.js';
import { printError, printSuccess, printInfo, printHeader } from '../output.js';
async function handleList(world) {
    printHeader(`Lanes in world ${world}`);
    const result = await callHostCpProxy('GET', world, '/lanes');
    if (!result.ok) {
        printError(`List failed: ${result.error}`);
        if (result.status === 0) {
            printInfo('Hint', 'Is host CP running? `olam host-cp status`');
        }
        process.exitCode = 1;
        return;
    }
    const data = result.data;
    const lanes = data?.lanes ?? [];
    if (lanes.length === 0) {
        printInfo('Lanes', '(none — dispatch a task to spawn claude-main)');
        return;
    }
    for (const l of lanes) {
        const marker = l.isMain ? '◉' : '·';
        const taskPreview = l.task.length > 60 ? l.task.slice(0, 57) + '...' : l.task;
        printInfo(`${marker} ${l.name}`.padEnd(24), `${l.status.padEnd(8)} ${l.tmuxSession.padEnd(28)} ${taskPreview}`);
    }
}
async function handleCreate(world, opts) {
    printHeader(`Create lane ${opts.name} in ${world}`);
    const result = await callHostCpProxy('POST', world, '/lanes/create', {
        name: opts.name,
        task: opts.task,
    });
    if (!result.ok) {
        printError(`Create failed (HTTP ${result.status}): ${result.error}`);
        process.exitCode = 1;
        return;
    }
    const data = result.data;
    if (!data) {
        printError('Create succeeded but response body was empty');
        return;
    }
    printSuccess(`${data.action ?? 'created'} lane ${data.name} → ${data.tmuxSession} (${data.status})`);
}
async function handleDestroy(world, name) {
    printHeader(`Destroy lane ${name} in ${world}`);
    const result = await callHostCpProxy('DELETE', world, `/lanes/${encodeURIComponent(name)}`);
    if (!result.ok) {
        printError(`Destroy failed (HTTP ${result.status}): ${result.error}`);
        if (result.status === 404) {
            printInfo('Hint', 'Lane already gone? Check `olam lanes list <world>`.');
        }
        process.exitCode = 1;
        return;
    }
    printSuccess(`Destroyed lane ${name} (transcript retained)`);
}
async function handleDispatch(world, name, prompt) {
    printHeader(`Dispatch to lane ${name} in ${world}`);
    if (!prompt || prompt.trim().length === 0) {
        printError('prompt must be a non-empty string');
        process.exitCode = 1;
        return;
    }
    const result = await callHostCpProxy('POST', world, `/lanes/${encodeURIComponent(name)}/dispatch`, {
        prompt,
    });
    if (!result.ok) {
        printError(`Dispatch failed (HTTP ${result.status}): ${result.error}`);
        if (result.status === 503) {
            printInfo('Hint', 'Lane exists but claude is not running. Try `olam lanes destroy` then re-create.');
        }
        process.exitCode = 1;
        return;
    }
    printSuccess(`Dispatched to ${name} (status accepted)`);
}
export function registerLanes(program) {
    const lanes = program
        .command('lanes')
        .description('Manage claude-lane-* tmux sessions inside a running world');
    lanes
        .command('list')
        .description('Enumerate lanes in a world')
        .argument('<world>', 'World id (e.g. ember-elk-8412)')
        .action((world) => handleList(world));
    lanes
        .command('create')
        .description('Spawn a new claude-lane-<name> session with an initial task')
        .argument('<world>', 'World id')
        .requiredOption('--name <name>', 'Lane name (lowercase + digits + hyphens)')
        .requiredOption('--task <task>', 'Initial task prompt sent to the new lane')
        .action((world, opts) => handleCreate(world, opts));
    lanes
        .command('destroy')
        .description("Kill a lane's tmux session (transcript retained)")
        .argument('<world>', 'World id')
        .argument('<name>', 'Lane name')
        .action((world, name) => handleDestroy(world, name));
    lanes
        .command('dispatch')
        .description('Re-prompt an existing lane')
        .argument('<world>', 'World id')
        .argument('<name>', 'Lane name')
        .argument('<prompt...>', 'Prompt to send (multi-arg joined with spaces)')
        .action((world, name, promptParts) => handleDispatch(world, name, promptParts.join(' ')));
}
//# sourceMappingURL=lanes.js.map