"use strict";

const path = require("node:path");
const { execFile } = require("node:child_process");

// This registry is intentionally small. Write or service actions require a
// separate reviewed entry and a matching deployment-receiver rule.
const REPO_ROOT = path.resolve(__dirname, "../../..");
const INSPECT_SCRIPT = path.join(REPO_ROOT, "server-tools/deployment-receiver/scripts/inspect-gatekeeper.js");

const ACTIONS = Object.freeze({
  "inspect-gatekeeper": Object.freeze({
    label: "只读检查 Gatekeeper",
    scope: "system-arch",
    mode: "read-only",
    run: (timeout) => runFile(process.execPath, [INSPECT_SCRIPT], timeout)
  }),
  "sync-status": Object.freeze({
    label: "只读检查第五域同步状态",
    scope: "code-repo",
    mode: "read-only",
    run: (timeout) => runFile("/usr/bin/git", ["-C", REPO_ROOT, "status", "--short", "--branch"], timeout)
  })
});

function runFile(file, args, timeout) {
  return new Promise((resolve) => {
    execFile(file, args, { timeout: timeout || 30000, maxBuffer: 100000 }, (err, stdout, stderr) => {
      resolve({
        code: err ? (typeof err.code === "number" ? err.code : 1) : 0,
        stdout: (stdout || "").slice(0, 100000),
        stderr: (stderr || "").slice(0, 100000)
      });
    });
  });
}

function getAction(action) {
  return typeof action === "string" ? ACTIONS[action] || null : null;
}

function listActions() {
  return Object.entries(ACTIONS).map(([id, action]) => ({ id, label: action.label, scope: action.scope, mode: action.mode }));
}

module.exports = { getAction, listActions, INSPECT_SCRIPT };
