import { execSync } from "child_process";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { getLoadAnimation } from "./utils/index.mjs";

const loadAnimation = getLoadAnimation("正在启动应用...");

// 基础路径配置
const dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.join(dirname, "../");

try {
  loadAnimation.start();

  // 检查 turbo 是否可用
  try {
    execSync("turbo --version", { stdio: "ignore" });
  } catch {
    loadAnimation.stop();
    console.error("❌ 未找到 turbo，请先执行以下命令安装：");
    console.log("npm install -g turbo");
    process.exit(1);
  }

  const { spawn } = await import("child_process");
  const child = spawn("turbo", ["run", "dev"], {
    stdio: "inherit",
    cwd: rootDir,
    shell: true, // 启用 shell 解析
    env: {
      ...process.env,
      PATH: `${process.env.PATH}:${path.join(rootDir, "node_modules/.bin")}`,
    },
  });

  // 增加错误事件监听
  child.on("error", (err) => {
    loadAnimation.fail(`启动失败: ${err.message}`);
    process.exit(1);
  });

  console.log("🚀 执行命令: turbo run dev");

  // 监听子进程退出
  child.on("exit", (code) => {
    if (code === 0) {
      loadAnimation.succeed("应用启动成功");
    } else {
      loadAnimation.fail(`应用异常退出，代码 ${code}`);
    }
    process.exit(code || 0); // 确保父进程退出
  });

  // 监听终止信号
  process.on("SIGINT", () => {
    loadAnimation.stop();
    console.log("\n🛑 收到终止信号，正在清理进程...");
    child.kill("SIGINT"); // 先终止子进程
    process.exit(0);
  });
} catch (error) {
  loadAnimation.stop();
  if (error.message.includes("User force closed the prompt")) {
    console.log("\n🚪 已主动退出程序");
  } else {
    console.error("执行错误:", error.message);
  }
  process.exit(0);
} finally {
  loadAnimation.stop();
}

// 保留全局异常处理
process.on("uncaughtException", (error) => {
  loadAnimation.stop();
  console.error("未捕获异常:", error.message);
  process.exit(1);
});

// 保留终止信号处理
process.on("SIGINT", () => {
  loadAnimation.stop();
  console.log("\n🛑 收到终止信号");
  process.exit(0);
});
