/**
 * olam list — List all active worlds.
 */
import pc from 'picocolors';
import { loadContext } from '../context.js';
import { printError, formatAge } from '../output.js';
/** Lifecycle statuses accepted by `--status`. Mirrors WorldLifecycleStatus. */
const VALID_STATUSES = [
    'creating',
    'running',
    'paused',
    'crystallizing',
    'destroyed',
    'error',
];
/**
 * Pure renderer for `olam list`. Returns the lines to print so the
 * formatting + JSON contract is unit-testable without touching the
 * world registry or process I/O.
 */
export function renderWorldList(worlds, opts = {}) {
    if (opts.json) {
        return JSON.stringify(worlds.map((w) => ({
            id: w.id,
            name: w.name,
            status: w.status,
            repos: [...w.repos],
            totalCostUsd: w.totalCostUsd,
            createdAt: w.createdAt,
        })));
    }
    if (worlds.length === 0) {
        return pc.dim('No worlds. Create one with `olam create --name my-world`.');
    }
    const lines = [`${pc.bold(String(worlds.length))} world(s)\n`];
    for (const w of worlds) {
        const statusColor = w.status === 'running'
            ? pc.green(w.status)
            : w.status === 'error'
                ? pc.red(w.status)
                : pc.yellow(w.status);
        const age = formatAge(w.createdAt);
        const cost = `$${w.totalCostUsd.toFixed(2)}`;
        lines.push(`  ${pc.bold(w.name)} ${pc.dim(`(${w.id})`)}`);
        lines.push(`    ${statusColor}  ${pc.dim('|')}  ${w.repos.join(', ')}  ${pc.dim('|')}  ${cost}  ${pc.dim('|')}  ${age}`);
        lines.push('');
    }
    return lines.join('\n');
}
/** Normalise + validate a `--status` value. Returns null when unset. */
export function parseStatusFilter(raw) {
    if (raw === undefined)
        return { status: null };
    const normalised = raw.trim().toLowerCase();
    if (VALID_STATUSES.includes(normalised)) {
        return { status: normalised };
    }
    return {
        status: null,
        error: `Unknown status "${raw}". Valid values: ${VALID_STATUSES.join(', ')}.`,
    };
}
export function registerList(program) {
    program
        .command('list')
        .alias('ls')
        .description('List active worlds')
        .option('--json', 'Emit machine-readable JSON instead of the text table', false)
        .option('--status <status>', `Only show worlds with this lifecycle status (${VALID_STATUSES.join(', ')})`)
        .action(async (raw) => {
        const { status, error: statusError } = parseStatusFilter(raw.status);
        if (statusError) {
            printError(statusError);
            process.exitCode = 1;
            return;
        }
        const { ctx, error } = await loadContext();
        if (!ctx) {
            printError(error?.message ?? 'Olam is not configured. Run `olam init` first.');
            process.exitCode = 1;
            return;
        }
        const worlds = ctx.worldManager.listWorlds(status ? { status } : undefined);
        console.log(renderWorldList(worlds, { json: raw.json === true }));
    });
}
//# sourceMappingURL=list.js.map