import readline from "readline";

let initialized = false;
let currentHandler = null;

function ensureRawMode(enabled) {
  if (process.stdin.isTTY) {
    process.stdin.setRawMode(enabled);
  }
}

export function initKeypress() {
  // 清理所有keypress监听器
  process.stdin.removeAllListeners("keypress");
  currentHandler = null;

  // 初始化readline（只需一次）
  if (!initialized) {
    readline.emitKeypressEvents(process.stdin);
    initialized = true;
  }

  ensureRawMode(true);
}

export function onKey(handler) {
  // 清理旧的监听器
  process.stdin.removeAllListeners("keypress");
  currentHandler = handler;
  process.stdin.on("keypress", handler);
}

export function stopKeypress() {
  process.stdin.removeAllListeners("keypress");
  currentHandler = null;
  ensureRawMode(false);
}

export function waitForKey(message = "按任意键返回...") {
  return new Promise(resolve => {
    console.log("\n" + message);
    initKeypress();
    onKey(() => {
      stopKeypress();
      resolve();
    });
  });
}
