#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.main = main;
const app_lock_file_1 = require("../apps/app-lock-file");
const manifest_1 = require("../apps/manifest");
const workspace_app_state_1 = require("../apps/workspace-app-state");
const rtws_1 = require("../rtws");
const apps_cli_hints_1 = require("./apps-cli-hints");
function printHelp() {
    console.log(`Usage:
  dominds update [<appId>]

Notes:
  - Re-runs dynamic app resolution using .minds/app.yaml + .apps/configuration.yaml.
  - Refreshes derived state in .apps/resolution.yaml and .minds/app-lock.yaml.
  - update recomputes derived state; it does not explain root-cause mismatches in
    declaration, disabled state, resolution snapshots, or handshake entry fields.
  - ${(0, apps_cli_hints_1.formatMutationBoundaryNote)({
        commandName: 'update',
        layerDescription: '.minds/app-lock.yaml and .apps/resolution.yaml derived state',
    })}
`);
}
function parseArgs(argv) {
    const positional = [];
    for (const arg of argv) {
        if (arg === '--help' || arg === '-h') {
            printHelp();
            process.exit(0);
        }
        if (arg.startsWith('-'))
            throw new Error(`Unknown option: ${arg}`);
        positional.push(arg);
    }
    if (positional.length > 1)
        throw new Error('update accepts at most one <appId>');
    return { appId: positional[0] ?? null };
}
async function main(argv = process.argv.slice(2)) {
    let args;
    try {
        args = parseArgs(argv);
    }
    catch (err) {
        console.error(err instanceof Error ? err.message : String(err));
        printHelp();
        process.exit(1);
        return;
    }
    const rtwsRootAbs = (0, rtws_1.domindsRtwsRootAbs)();
    if (args.appId !== null &&
        !(await (0, manifest_1.hasRtwsDeclaredAppDependency)({ rtwsRootAbs, appId: args.appId }))) {
        console.error(`Error: app '${args.appId}' is not declared in .minds/app.yaml dependencies`);
        console.error((0, apps_cli_hints_1.formatDoctorGuidance)({ appId: args.appId }));
        process.exit(1);
        return;
    }
    const resolution = await (0, workspace_app_state_1.refreshAppsDerivedState)({ rtwsRootAbs });
    const loadedLock = await (0, app_lock_file_1.loadAppLockFile)({ rtwsRootAbs });
    if (loadedLock.kind === 'error') {
        console.error(`Error: failed to read .minds/app-lock.yaml: ${loadedLock.errorText}`);
        console.error((0, apps_cli_hints_1.formatDoctorGuidance)({ appId: args.appId }));
        process.exit(1);
        return;
    }
    let nextLock = loadedLock.file;
    for (const app of resolution.apps) {
        if (args.appId !== null && app.id !== args.appId)
            continue;
        nextLock = (0, app_lock_file_1.upsertLockedApp)({
            existing: nextLock,
            next: {
                id: app.id,
                package: {
                    name: app.installJson.package.name,
                    version: app.installJson.package.version,
                },
            },
        });
    }
    await (0, app_lock_file_1.writeAppLockFileIfChanged)({ rtwsRootAbs, file: nextLock });
    if (args.appId === null) {
        for (const app of resolution.apps) {
            console.log(`Updated app '${app.id}' derived state in .minds/app-lock.yaml and .apps/resolution.yaml.`);
        }
        console.log((0, apps_cli_hints_1.formatMutationBoundaryNote)({
            commandName: 'update',
            layerDescription: '.minds/app-lock.yaml and .apps/resolution.yaml derived state',
        }));
        return;
    }
    console.log(`Updated app '${args.appId}' derived state in .minds/app-lock.yaml and .apps/resolution.yaml.`);
    console.log((0, apps_cli_hints_1.formatMutationBoundaryNote)({
        commandName: 'update',
        layerDescription: '.minds/app-lock.yaml and .apps/resolution.yaml derived state',
        appId: args.appId,
    }));
}
if (require.main === module) {
    main().catch((err) => {
        console.error('Unhandled error:', err);
        process.exit(1);
    });
}
