import { existsSync, rmSync } from 'node:fs';
import { createInterface } from 'node:readline';
import {
  GATEWAY_HOME,
  getDaemonPid,
  readMeta,
  stopDaemon,
  uninstallGatewayPackage,
} from './daemon.js';

export async function runUninstall(): Promise<void> {
  const rl = createInterface({ input: process.stdin, output: process.stdout });
  try {
    await doUninstall(rl);
  } finally {
    rl.close();
  }
}

function prompt(rl: ReturnType<typeof createInterface>, question: string): Promise<string> {
  return new Promise((resolve) => rl.question(question, resolve));
}

async function doUninstall(rl: ReturnType<typeof createInterface>): Promise<void> {
  const meta = readMeta();
  if (!meta) {
    console.log('Gateway is not installed.');
    return;
  }

  const answer = await prompt(rl, 'Uninstall Mosaic Gateway? [y/N] ');
  if (answer.toLowerCase() !== 'y') {
    console.log('Aborted.');
    return;
  }

  // Stop if running
  if (getDaemonPid() !== null) {
    console.log('Stopping gateway daemon...');
    try {
      await stopDaemon();
      console.log('Stopped.');
    } catch (err) {
      console.warn(`Warning: ${err instanceof Error ? err.message : String(err)}`);
    }
  }

  // Remove config/data
  const removeData = await prompt(rl, `Remove all gateway data at ${GATEWAY_HOME}? [y/N] `);
  if (removeData.toLowerCase() === 'y') {
    if (existsSync(GATEWAY_HOME)) {
      rmSync(GATEWAY_HOME, { recursive: true, force: true });
      console.log('Gateway data removed.');
    }
  }

  // Uninstall npm package
  console.log('Uninstalling npm package...');
  uninstallGatewayPackage();

  console.log('\nGateway uninstalled.');
}
