/**
 * `madarx uninstall` — remove the global install.
 *
 * Removes the npm package (`npm rm -g madarx`). The data home (~/.madarx)
 * is KEPT by default — it holds your DB, workspace, and secrets vault key. Pass
 * --purge to also delete it (guarded by an explicit confirm). The npm runner is
 * injectable for tests so this never shells out under `npm test`.
 */

import fs from 'node:fs';
import { spawn } from 'node:child_process';
import { createInterface } from 'node:readline/promises';
import { PKG_NAME } from '../update-check.js';
import { resolveHome } from './home.js';

function npmGlobalRemove(pkg) {
  return new Promise((resolve) => {
    const child = spawn('npm', ['rm', '-g', pkg, '--no-audit', '--no-fund'], { stdio: 'inherit' });
    child.on('error', (err) => resolve({ ok: false, code: -1, output: String(err.message) }));
    child.on('exit', (code) => resolve({ ok: code === 0, code }));
  });
}

async function confirm(prompt, dfltYes = false) {
  if (!(process.stdin.isTTY && process.stdout.isTTY)) return dfltYes;
  const rl = createInterface({ input: process.stdin, output: process.stdout });
  const ans = (await rl.question(`${prompt} ${dfltYes ? '[Y/n]' : '[y/N]'}: `)).trim().toLowerCase();
  rl.close();
  if (!ans) return dfltYes;
  return ans === 'y' || ans === 'yes';
}

export async function uninstall({ flags = {}, runner = npmGlobalRemove } = {}) {
  const layout = resolveHome();
  const yes = Boolean(flags.yes || flags.y);
  const purge = Boolean(flags.purge);

  console.log('madarx uninstall\n');
  if (!yes && !(await confirm(`Remove the global ${PKG_NAME} package?`, false))) {
    console.log('Cancelled.');
    return 0;
  }

  const res = await runner(PKG_NAME);
  if (!res.ok) {
    console.error(`\nnpm rm failed (exit ${res.code}). If your prefix needs sudo, run: npm rm -g ${PKG_NAME}`);
    return 1;
  }
  console.log(`Removed ${PKG_NAME}.`);

  if (purge) {
    const ok = yes || (await confirm(`Also DELETE your data home (${layout.home})? This erases the DB, workspace, and vault key.`, false));
    if (ok) {
      try { fs.rmSync(layout.home, { recursive: true, force: true }); console.log(`Deleted ${layout.home}.`); }
      catch (err) { console.error(`Could not delete ${layout.home}: ${err.message}`); }
    } else {
      console.log(`Kept ${layout.home}.`);
    }
  } else {
    console.log(`Your data is kept at ${layout.home} (use --purge to remove it).`);
  }
  return 0;
}
