import inquirer from "inquirer";
import { execSync } from "child_process";
import path from "node:path";
import fs from "node:fs";
import { fileURLToPath } from "node:url";

// 修正后的目录获取逻辑
const dirname = path.dirname(fileURLToPath(import.meta.url));
const EXCLUDE_FILES = ["index.mjs", "utils"]; // 排除自身和其他非命令文件

// 获取当前目录下的命令文件
const commands = fs
  .readdirSync(dirname) // 直接读取当前目录
  .filter((file) => {
    const fullPath = path.join(dirname, file);
    return (
      fs.statSync(fullPath).isFile() &&
      !EXCLUDE_FILES.includes(file) &&
      path.extname(file) === ".mjs"
    );
  })
  .map((file) => ({
    name: `📦 ${path.basename(file, ".mjs")}`,
    value: path.basename(file, ".mjs"),
  }));

// 提供交互式选择
inquirer
  .prompt([
    {
      type: "list",
      name: "command",
      message: "选择要执行的命令",
      choices: commands,
    },
  ])
  .then((answers) => {
    console.log("answers", answers);
    // 获取用户选择的命令
    const selectedCommand = `node ${path.join(dirname, answers.command)}.mjs`;

    // 执行 Bash 命令
    console.log("🚀 执行命令:", selectedCommand); // 添加命令预览
    try {
      execSync(selectedCommand, {
        stdio: "inherit",
        // 添加终止信号处理
        killSignal: "SIGTERM",
        timeout: 0,
      });
    } catch (error) {
      console.log("error", error);
      if (error.signal === "SIGTERM") {
        console.log("\n🛑 命令执行被终止");
      } else {
        console.log("\n🛑 执行错误，错误堆栈：", error.stack, error.message);
      }
    }
  })
  .catch((error) => {
    if (error.isTtyError) {
      console.log("\n👋 终端环境异常");
    } else if (error.message.includes("User force closed the prompt")) {
      console.log("\n🚪 已主动退出程序");
    } else {
      console.error("执行错误:", error.message);
    }
    process.exit(0); // 确保进程正常退出
  });

// 添加全局未捕获异常处理
process.on("uncaughtException", (error) => {
  if (error.message.includes("User force closed the prompt")) {
    console.log("\n🔌 连接已断开");
    process.exit(0);
  }
});

// 添加 SIGINT 监听
process.on("SIGINT", () => {
  console.log("\n🛑 收到终止信号");
  process.exit(0);
});
