import { listModels } from './providers/openrouter.js';
import { runAgent } from './agent/loop.js';
import { buildSystemPrompt } from './agent/prompt.js';
import { saveSession } from './sessions.js';
import { assembleTools } from './tools/assemble.js';
import { PermissionGate } from './permissions.js';
/**
 * One-shot mode: run a single task to completion and print output to stdout.
 * Without --yolo, only read-only tools are allowed (no TTY to ask approval).
 */
export async function runPrintMode(opts) {
    const messages = [
        ...(opts.initialMessages ?? [{ role: 'system', content: buildSystemPrompt(opts.cwd) }]),
        { role: 'user', content: opts.prompt },
    ];
    const contextLength = await listModels(opts.apiKey)
        .then((models) => models.find((m) => m.id === opts.model)?.contextLength ?? null)
        .catch(() => null);
    const gate = new PermissionGate(async () => 'no', // non-interactive: deny anything that needs approval
    opts.yolo);
    const tools = assembleTools({
        apiKey: opts.apiKey,
        provider: opts.provider,
        getModel: () => opts.model,
        gate,
        mcpTools: opts.mcpTools,
        cwd: opts.cwd,
    });
    const controller = new AbortController();
    process.on('SIGINT', () => controller.abort());
    let hadError = false;
    const events = runAgent({
        apiKey: opts.apiKey,
        model: opts.model,
        provider: opts.provider,
        messages,
        tools,
        gate,
        ctx: { cwd: opts.cwd },
        signal: controller.signal,
        hooks: opts.hooks,
        contextLength,
    });
    for await (const ev of events) {
        switch (ev.type) {
            case 'assistant-delta':
                process.stdout.write(ev.text);
                break;
            case 'assistant-message':
                process.stdout.write('\n');
                break;
            case 'tool-start':
                process.stderr.write(`[tool] ${ev.name}${ev.summary ? `: ${ev.summary}` : ''}\n`);
                break;
            case 'tool-result':
                if (ev.isError)
                    process.stderr.write(`[tool error] ${ev.result.slice(0, 300)}\n`);
                break;
            case 'compacted':
                process.stderr.write(`[auto-compacted ${ev.summarizedCount} older messages]\n`);
                break;
            case 'error':
                process.stderr.write(`error: ${ev.message}\n`);
                hadError = true;
                break;
            case 'done':
                if (ev.reason === 'cancelled')
                    process.stderr.write('cancelled\n');
                if (ev.reason !== 'complete')
                    hadError = true;
                break;
        }
    }
    saveSession(opts.cwd, opts.model, messages);
    return hadError ? 1 : 0;
}
