"use strict";

const fs = require("node:fs");
const crypto = require("node:crypto");
const { execFileSync } = require("node:child_process");

const candidates = [
  "/opt/zhuyuan/gatekeeper/engine-v3.js",
  "/opt/engine.js"
];

function digest(file) {
  return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
}

function pm2Info() {
  try {
    const list = JSON.parse(execFileSync("/usr/bin/env", ["pm2", "jlist"], { encoding: "utf8", timeout: 10000 }));
    return list.filter((item) => /engine|gatekeeper/i.test(item.name || "")).map((item) => ({
      name: item.name,
      status: item.pm2_env?.status,
      script: item.pm2_env?.pm_exec_path,
      restart_time: item.pm2_env?.restart_time,
      started_at: item.pm2_env?.pm_uptime ? new Date(item.pm2_env.pm_uptime).toISOString() : null
    }));
  } catch (error) {
    return [{ error: error.message.slice(0, 300) }];
  }
}

const files = candidates.filter((file) => fs.existsSync(file)).map((file) => {
  const source = fs.readFileSync(file, "utf8");
  return {
    path: file,
    sha256: digest(file),
    contains_direct_email_mode: source.includes("requestEmail") || source.includes("email_mode: requestEmail"),
    contains_hmac_headers: source.includes("X-Sovereign") && source.includes("X-Minute"),
    contains_auth_request: source.includes("/auth/request"),
    contains_exec_route: source.includes("/exec")
  };
});

process.stdout.write(`${JSON.stringify({
  ok: true,
  checked_at: new Date().toISOString(),
  hostname: require("node:os").hostname(),
  files,
  pm2: pm2Info()
}, null, 2)}\n`);
