#!/usr/bin/env node
import color from "picocolors";
import { execSync } from "child_process";
import { createRequire } from "module";
import { showMainMenu, setUpdateInfo } from "./lib/menu.js";
import { checkUpdate } from "./lib/update.js";

const require = createRequire(import.meta.url);
const pkg = require("./package.json");

const updateResult = await checkUpdate();
if (updateResult) {
  setUpdateInfo(updateResult);
}

while (true) {
  const selected = await showMainMenu();

  console.clear();

  if (selected.isUpdate) {
    console.log(color.cyan("\n正在更新...\n"));
    try {
      execSync(`npm i -g ${pkg.name}@latest`, { stdio: "inherit" });
      console.log(color.green("\n✅ 更新完成！请重新运行 yinx\n"));
      process.exit(0);
    } catch {
      console.log(color.red("\n❌ 更新失败，请手动运行: npm i -g " + pkg.name + "@latest\n"));
      process.exit(1);
    }
  }

  console.log(color.cyan("\n正在启动: " + selected.name + "...\n"));

  try {
    const runner = selected.run || selected.tool?.run;
    if (typeof runner !== "function") {
      throw new Error("当前菜单项缺少 run 方法");
    }
    const result = await runner();
    if (result === "back") continue;
    break;
  } catch (err) {
    console.log(color.yellow("\n⚠️ " + selected.name + " 模块尚未实现"));
    console.log(color.dim(err.message));
    console.log(color.dim("\n按任意键返回主菜单..."));
    await new Promise(resolve => {
      process.stdin.setRawMode(true);
      process.stdin.once("data", () => {
        process.stdin.setRawMode(false);
        resolve();
      });
    });
  }
}
