/**
 * Shared interactive-routing + browse loop for the task-first session
 * pickers (`browser-sessions-picker.ts`, `computer-sessions-picker.ts`).
 *
 * Each twin keeps its own row formatter, matcher, and enter-handler; this
 * factory owns the TTY/`--json`/`--no-interactive` (and optional `--open`)
 * gate, the empty-list message, and the cancel-aware `itemPicker` loop.
 */
import { itemPicker } from '../lib/picker.js';
import { isInteractiveTerminal, isPromptCancelled } from './utils.js';
export function shouldOpenInteractiveSessions(opts, isTTY, requireOpenUndefined = false) {
    return (opts.interactive !== false &&
        !opts.json &&
        (!requireOpenUndefined || opts.open === undefined) &&
        isTTY);
}
export async function browseSessionsUntilQuit(spec) {
    for (;;) {
        let picked;
        try {
            picked = await itemPicker({
                message: spec.message,
                items: spec.rows,
                filter: (query) => (query.trim() ? spec.rows.filter((r) => spec.matches(r, query)) : spec.rows),
                labelFor: spec.labelFor,
                buildPreview: spec.buildPreview,
                emptyMessage: spec.emptyFilterMessage,
                enterHint: spec.enterHint,
            });
        }
        catch (err) {
            if (isPromptCancelled(err))
                return;
            throw err;
        }
        if (!picked)
            return;
        await spec.onOpen(picked.item);
    }
}
export function createSessionsPickerCommand(spec) {
    const shouldOpen = (opts, isTTY) => shouldOpenInteractiveSessions(opts, isTTY, spec.requireOpenUndefined === true);
    return {
        shouldOpen,
        run: async (opts) => {
            if (!shouldOpen(opts, isInteractiveTerminal())) {
                await spec.runFlat(opts);
                return;
            }
            const rows = spec.buildRows(opts);
            if (rows.length === 0) {
                console.log(spec.emptyMessage(opts));
                return;
            }
            await browseSessionsUntilQuit({
                message: spec.message,
                rows,
                matches: spec.matches,
                labelFor: spec.labelFor,
                buildPreview: spec.buildPreview,
                emptyFilterMessage: spec.emptyFilterMessage,
                enterHint: spec.enterHint,
                onOpen: spec.onOpen,
            });
        },
    };
}
