/**
 * olam world upgrade [<slug>] [--all] [--dry-run] — Refresh the CLI version
 * pin in <world>/.olam/world.yaml (Phase D, D4).
 *
 * Subcommand of `olam world`. Uses the same stampVersionPin() helper as D3's
 * version check. Idempotent: already-current pins are no-ops.
 */
import { printError, printInfo, printHeader } from '../output.js';
import { getOrCreateWorldCommand } from './world.js';
import { stampVersionPin, CLI_VERSION } from '@olam/core/src/world/version-pin.js';
/**
 * Upgrade logic, injectable for testing.
 * Returns a list of results (one per world processed).
 */
export async function doWorldUpgrade(opts) {
    const version = opts.version ?? CLI_VERSION;
    const stamp = opts.stampPin ?? ((p, v) => stampVersionPin(p, v));
    let targets;
    if (opts.all) {
        targets = opts.getWorlds();
    }
    else if (opts.slug) {
        const w = opts.getWorld(opts.slug);
        if (!w)
            return [];
        targets = [w];
    }
    else {
        return [];
    }
    return targets.map((w) => {
        const stamped = opts.dryRun ? false : stamp(w.workspacePath, version);
        return { worldId: w.id, stamped, dryRun: opts.dryRun === true };
    });
}
export function registerWorldUpgrade(program) {
    const world = getOrCreateWorldCommand(program);
    world
        .command('upgrade [slug]')
        .description('Refresh cli_version pin in world.yaml to current CLI version')
        .option('--all', 'Upgrade all worlds')
        .option('--dry-run', 'Preview which worlds would be upgraded without writing')
        .action(async (slug, opts) => {
        const { loadContext } = await import('../context.js');
        const { ctx, error } = await loadContext();
        if (!ctx) {
            printError(error?.message ?? 'Olam is not configured. Run `olam init` first.');
            process.exitCode = 1;
            return;
        }
        if (!slug && !opts.all) {
            printError('Specify a world slug or --all.');
            process.exitCode = 1;
            return;
        }
        const results = await doWorldUpgrade({
            slug,
            all: opts.all,
            dryRun: opts.dryRun,
            getWorlds: () => ctx.worldManager.listWorlds(),
            getWorld: (id) => ctx.worldManager.getWorld(id),
        });
        if (results.length === 0) {
            printError(`World "${slug}" not found.`);
            process.exitCode = 1;
            return;
        }
        printHeader(`World upgrade ${opts.dryRun ? '(dry run)' : ''}`);
        for (const r of results) {
            if (opts.dryRun) {
                printInfo(r.worldId, 'would upgrade');
            }
            else if (r.stamped) {
                printInfo(r.worldId, `stamped → v${CLI_VERSION}`);
            }
            else {
                printInfo(r.worldId, `already at v${CLI_VERSION} (no-op)`);
            }
        }
    });
}
//# sourceMappingURL=world-upgrade.js.map