/**
 * nexus-prime reset — clear TRANSIENT runtime/session state.
 *
 * Stops the daemon, removes lockfiles, and wipes the ephemeral `runs/` dir.
 * It does NOT remove memories, workforce DBs, IDE registrations, or setup
 * markers — that's what `nexus-prime uninstall` is for.
 *
 * Legacy flags `--hard` and `--wipe-memories` / `--unregister` still parse so
 * existing scripts don't break, but they now print a one-line pointer to
 * `uninstall --purge-all` and otherwise behave the same as the transient reset.
 */
import * as fs from 'fs';
import * as path from 'path';
import * as readline from 'readline';
import { runPostinstallCleanup } from '../postinstall/cleanup.js';
import { resolveNexusStateDir } from '../engines/runtime-registry.js';
import { resolveWorkspaceStateRoot } from '../engines/workspace-resolver.js';
import { unregisterNexusRegistrations } from './uninstall.js';
// ── helpers ───────────────────────────────────────────────────────────────────
function prompt(question) {
    return new Promise((resolve) => {
        const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
        rl.question(question, (answer) => {
            rl.close();
            resolve(answer.trim().toLowerCase() === 'y' || answer.trim().toLowerCase() === 'yes');
        });
    });
}
// ── main export ───────────────────────────────────────────────────────────────
export async function runReset(options) {
    const summary = {
        daemonsKilled: 0,
        lockfilesRemoved: 0,
        dbFilesDeleted: 0,
        runDirsDeleted: 0,
        registrationsRemoved: 0,
        ok: false,
    };
    if (!options.hard && !options.soft) {
        console.error('[reset] specify --hard or --soft');
        return summary;
    }
    if (options.hard && options.soft) {
        console.error('[reset] specify either --hard or --soft, not both');
        return summary;
    }
    if (options.hard || options.wipeMemories) {
        console.log('');
        console.log('  ℹ  `reset` now clears only transient runtime state.');
        console.log('     For full removal (memories, workforce DBs, IDE registrations, markers):');
        console.log('         nexus-prime uninstall --purge --yes');
        console.log('');
    }
    // Resolve the stateRoot to wipe
    const nexusDir = resolveNexusStateDir();
    const stateRoot = options.workspace
        ? path.join(nexusDir, 'workspaces', options.workspace)
        : resolveWorkspaceStateRoot(process.cwd());
    const target = options.workspace
        ? `workspace ${options.workspace}`
        : path.relative(process.env.HOME ?? '/', stateRoot).replace(/^\.\.\//, '~/../');
    if (!options.yes && !options._forceYes) {
        console.log(`\n⚠️  This will STOP the nexus-prime daemon, clear lockfiles and scratch runs for ${target}.`);
        console.log('    Memories, workforce DBs, and IDE registrations are preserved.');
        const confirmed = await prompt('  Proceed? [y/N] ');
        if (!confirmed) {
            console.log('  Aborted.');
            return summary;
        }
    }
    console.log(`\n[reset] Clearing transient state for ${stateRoot} …`);
    // Step 1: kill daemon + remove lockfiles
    const cleanup = await runPostinstallCleanup({ silent: false });
    summary.daemonsKilled = cleanup.staleDaemonsKilled;
    summary.lockfilesRemoved = cleanup.staleLockfilesRemoved;
    console.log(`  ✓ cleanup: ${summary.daemonsKilled} daemons killed, ${summary.lockfilesRemoved} lockfiles removed`);
    if (options.unregister) {
        const unregister = unregisterNexusRegistrations({
            workspaceRoot: process.cwd(),
            dryRun: false,
        });
        summary.registrationsRemoved = unregister.registrationsRemoved;
        console.log(`  ✓ unregister: ${summary.registrationsRemoved} registration(s) cleared`);
    }
    // Step 2: delete the runs dir (transient only — per-session scratch)
    const runsDir = path.join(stateRoot, 'runs');
    try {
        if (fs.existsSync(runsDir)) {
            fs.rmSync(runsDir, { recursive: true, force: true });
            summary.runDirsDeleted = 1;
            console.log('  ✓ deleted runs/');
        }
    }
    catch (err) {
        console.error(`  ! could not remove runs/: ${err.message}`);
    }
    summary.ok = true;
    console.log('\n[reset] Transient state cleared.');
    console.log('        Run `nexus-prime uninstall --dry-run` to preview full removal.');
    return summary;
}
