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

// 替换原有的 __dirname 定义
const dirname = path.dirname(fileURLToPath(import.meta.url));

// 获取 apps 目录
const appsDir = path.join(dirname, "../apps");

const EXCLUDE_DIRS = ["platform"];
// 通过 apps 目录生成 commands 对象
try {
  const commands = fs
    .readdirSync(appsDir)
    .filter((app) => {
      const isDirectory = fs.statSync(path.join(appsDir, app)).isDirectory();
      return isDirectory && !EXCLUDE_DIRS.includes(app);
    })
    .map((app) => ({
      name: `📦 ${app}`, // 显示带图标的友好名称
      value: app, // 实际值保持原目录名
    }));

  // console.log(commands);

  // 提供交互式选择
  inquirer
    .prompt([
      {
        type: "list",
        name: "command",
        message: "选择要独立运行的子应用",
        choices: commands,
      },
    ])
    .then(async (answers) => {
      const command = `turbo run dev --filter=@sy/low-code-${answers.command}`;

      // 使用 spawn 替代 execSync
      const { spawn } = await import("child_process");
      const child = spawn(command.split(" ")[0], command.split(" ").slice(1), {
        stdio: "inherit",
        cwd: path.join(appsDir, ".."),
        shell: true,
        env: {
          ...process.env,
          PATH: `${process.env.PATH}:${path.join(appsDir, "../node_modules/.bin")}`,
        },
      });

      // 添加子进程事件监听
      child.on("error", (err) => {
        process.exit(1);
      });

      child.on("exit", (code) => {
        if (code === 0) {
        } else {
        }
        process.exit(code || 0);
      });

      // 修改 SIGINT 处理逻辑
      process.on("SIGINT", () => {
        console.log("\n🛑 正在终止子应用进程...");
        child.kill("SIGINT");
        process.exit(0);
      });
    })
    .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);
    });
} finally {
}

// 添加全局异常处理
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);
});
