#!/usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.main = main;
const promises_1 = __importDefault(require("node:fs/promises"));
const app_id_1 = require("../apps/app-id");
const app_lock_file_1 = require("../apps/app-lock-file");
const configuration_file_1 = require("../apps/configuration-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 uninstall <appId> [--purge]

Options:
  --purge   Also delete rtws app state directory: .apps/<appId path segments>/

Notes:
  - uninstall removes the app from .minds/app.yaml dependencies, clears its lock/config disabled state,
    and refreshes derived state.
  - ${(0, apps_cli_hints_1.formatMutationBoundaryNote)({
        commandName: 'uninstall',
        layerDescription: '.minds/app.yaml plus app-specific lock/configuration entries and derived resolution state',
    })}
`);
}
function parseArgs(argv) {
    const positional = [];
    let purge = false;
    for (const arg of argv) {
        if (arg === '--help' || arg === '-h') {
            printHelp();
            process.exit(0);
        }
        if (arg === '--purge') {
            purge = true;
            continue;
        }
        if (arg.startsWith('-'))
            throw new Error(`Unknown option: ${arg}`);
        positional.push(arg);
    }
    if (positional.length !== 1)
        throw new Error('uninstall requires exactly one <appId>');
    return { appId: positional[0], purge };
}
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)();
    const loadedManifest = await (0, manifest_1.loadDomindsAppManifest)({
        packageRootAbs: rtwsRootAbs,
        manifestRelPath: manifest_1.DEFAULT_DOMINDS_APP_MANIFEST_REL_PATH,
    });
    const manifest = loadedManifest.kind === 'ok' ? loadedManifest.manifest : (0, manifest_1.makeDefaultRtwsAppManifest)();
    const nextManifest = (0, manifest_1.removeManifestDependency)({
        manifest,
        dependencyId: args.appId,
    });
    if (nextManifest === manifest) {
        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;
    }
    await (0, manifest_1.writeDomindsAppManifestIfChanged)({
        packageRootAbs: rtwsRootAbs,
        manifestRelPath: manifest_1.DEFAULT_DOMINDS_APP_MANIFEST_REL_PATH,
        manifest: nextManifest,
    });
    const loadedConfig = await (0, configuration_file_1.loadAppsConfigurationFile)({ rtwsRootAbs });
    if (loadedConfig.kind === 'error') {
        console.error(`Error: failed to read .apps/configuration.yaml: ${loadedConfig.errorText}`);
        console.error((0, apps_cli_hints_1.formatDoctorGuidance)({ appId: args.appId }));
        process.exit(1);
        return;
    }
    const nextConfig = (0, configuration_file_1.setAppDisabledInConfiguration)({
        existing: loadedConfig.file,
        appId: args.appId,
        disabled: false,
    });
    await (0, configuration_file_1.writeAppsConfigurationFileIfChanged)({ rtwsRootAbs, file: nextConfig });
    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;
    }
    const nextLock = (0, app_lock_file_1.removeLockedApp)({ existing: loadedLock.file, appId: args.appId });
    await (0, app_lock_file_1.writeAppLockFileIfChanged)({ rtwsRootAbs, file: nextLock });
    await (0, workspace_app_state_1.refreshAppsDerivedState)({ rtwsRootAbs });
    if (args.purge) {
        const rtwsDirRel = (0, app_id_1.formatDomindsAppRtwsDirRel)(args.appId);
        const appDirAbs = (0, app_id_1.resolveDomindsAppRtwsDirAbs)(rtwsRootAbs, args.appId);
        await promises_1.default.rm(appDirAbs, { recursive: true, force: true });
        console.log(`Uninstalled app '${args.appId}' and purged rtws state directory ${rtwsDirRel}/.`);
    }
    else {
        console.log(`Uninstalled app '${args.appId}' while preserving rtws data under ${(0, app_id_1.formatDomindsAppRtwsDirRel)(args.appId)}/.`);
    }
    console.log((0, apps_cli_hints_1.formatMutationBoundaryNote)({
        commandName: 'uninstall',
        layerDescription: '.minds/app.yaml plus app-specific lock/configuration entries and derived resolution state',
        appId: args.appId,
    }));
}
if (require.main === module) {
    main().catch((err) => {
        console.error('Unhandled error:', err);
        process.exit(1);
    });
}
