/**
 * `olam skills migrate-hooks-back` — reverse Phase B B1 meta-hook
 * injection by restoring `~/.claude/settings.json` from a snapshot
 * written by `writeMetaHooksSnapshot` (engine writes one before every
 * injection that has a non-empty delta).
 *
 *   olam skills migrate-hooks-back [--snapshot <path>]
 *
 * Without `--snapshot`: consumes the most-recent
 * `meta-hooks-*.json` in `~/.olam/state/migration-snapshots/`.
 * With `--snapshot`: uses the named file explicitly.
 *
 * Output: prints settings.json path + snapshot path + summary
 * (restored / file-removed when snapshot represents pre-existence
 * absence) + exits 0 on success.
 */
import * as path from 'node:path';
import { findLatestMetaHooksSnapshot, readMetaHooksSnapshot, restoreSettingsFromSnapshot, migrationSnapshotsDir, META_HOOKS_SNAPSHOT_PREFIX, } from '@olam/core/src/skill-sources/meta-hooks-migration-snapshot.js';
import { claudeSettingsPath } from '@olam/core/src/skill-sources/index.js';
import { printError, printInfo, printSuccess } from '../output.js';
function asMessage(err) {
    return err instanceof Error ? err.message : String(err);
}
export function registerSkillsMigrateHooksBack(program) {
    const skills = program.commands.find((c) => c.name() === 'skills') ??
        program.command('skills').description('Manage skill sources and synchronization');
    skills
        .command('migrate-hooks-back')
        .description('Reverse olam-meta hook injection by restoring ~/.claude/settings.json from a B5 snapshot')
        .option('--snapshot <path>', 'Use a specific snapshot file (default: most recent meta-hooks-*.json)')
        .action((opts) => {
        try {
            const snapshotPath = opts.snapshot ?? findLatestMetaHooksSnapshot();
            if (!snapshotPath) {
                printError('No meta-hooks-* snapshot found in ~/.olam/state/migration-snapshots/. ' +
                    'Engine writes one before every injection that mutates settings.json; ' +
                    'if none exist, no reversible injection has happened yet.');
                process.exitCode = 1;
                return;
            }
            // CP3 HIGH-2 fix: when --snapshot is operator-supplied, the path
            // must (a) resolve inside ~/.olam/state/migration-snapshots/ and
            // (b) have the canonical `meta-hooks-` prefix. Without this
            // guard, an attacker (or accidental --snapshot /tmp/foo.json)
            // could supply an arbitrary JSON file → restoreSettingsFromSnapshot
            // would blindly write that JSON to ~/.claude/settings.json,
            // installing operator-attacker-chosen hook blocks.
            if (opts.snapshot) {
                const resolved = path.resolve(opts.snapshot);
                const allowedDir = path.resolve(migrationSnapshotsDir());
                if (!resolved.startsWith(allowedDir + path.sep)) {
                    printError(`--snapshot path must be inside ${allowedDir} (got "${resolved}"). ` +
                        `Refusing to restore from an arbitrary path — settings.json would land operator-chosen content.`);
                    process.exitCode = 1;
                    return;
                }
                const basename = path.basename(resolved);
                if (!basename.startsWith(META_HOOKS_SNAPSHOT_PREFIX)) {
                    printError(`--snapshot filename must start with "${META_HOOKS_SNAPSHOT_PREFIX}" (got "${basename}"). ` +
                        `Cross-namespace snapshots (atlas-toolbox-*) are not valid restore targets for olam-meta hooks.`);
                    process.exitCode = 1;
                    return;
                }
            }
            printInfo('snapshot', snapshotPath);
            const snapshot = readMetaHooksSnapshot(snapshotPath);
            printInfo('takenAt', snapshot.takenAt);
            const settingsFile = claudeSettingsPath();
            restoreSettingsFromSnapshot(snapshot, settingsFile);
            if (snapshot.originalSettings === null) {
                printSuccess(`removed ${settingsFile} (no settings.json existed pre-injection)`);
            }
            else {
                printSuccess(`restored ${settingsFile} to pre-injection state`);
            }
        }
        catch (err) {
            printError(asMessage(err));
            process.exitCode = 1;
        }
    });
}
//# sourceMappingURL=skills-migrate-hooks-back.js.map