"use strict";

const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const test = require("node:test");

const ROOT = path.resolve(__dirname, "../../..");
const MODULE = path.join(ROOT, "server-tools/light-lake-node-bootstrap");

function read(relative) {
  return fs.readFileSync(path.join(MODULE, relative), "utf8");
}

test("bootstrap declares the reproducible Guanghu node baseline", () => {
  const source = read("install.sh");
  for (const marker of [
    "Ubuntu 22.04",
    "x86_64",
    "NODE_ID",
    "/etc/guanghu/node.json",
    "/var/lib/guanghu/gatekeeper",
    "guanghu-gatekeeper.service",
    "node_20.x",
    "health-check.sh",
  ]) assert.match(source, new RegExp(marker.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));
});

test("bootstrap never opens Gatekeeper publicly", () => {
  const install = read("install.sh");
  const unit = read("guanghu-gatekeeper.service");
  assert.match(unit, /ENGINE_HOST=127\.0\.0\.1/);
  assert.doesNotMatch(install, /ufw\s+allow\s+3911/);
  assert.doesNotMatch(install, /0\.0\.0\.0:3911/);
});

test("template keeps secrets out of repository configuration", () => {
  const config = JSON.parse(read("node.example.json"));
  assert.equal(config.schema, "guanghu.node/v1");
  assert.ok(Array.isArray(config.roles));
  assert.equal("password" in config, false);
  assert.equal("private_key" in config, false);
  assert.equal("token" in config, false);
});

test("Gatekeeper runtime accepts explicit node identity, host and data directory", () => {
  const engine = fs.readFileSync(path.join(ROOT, "zero-point/core-channel/gatekeeper/engine-v3.js"), "utf8");
  assert.match(engine, /process\.env\.GATEKEEPER_SERVER_ID/);
  assert.match(engine, /process\.env\.ENGINE_HOST/);
  assert.match(engine, /process\.env\.GATEKEEPER_DATA_DIR/);
  assert.match(engine, /process\.env\.GATEKEEPER_SECRET_PATH/);
  assert.match(read("guanghu-gatekeeper.service"), /GATEKEEPER_SECRET_PATH=\/var\/lib\/guanghu\/gatekeeper\/secret/);
  assert.doesNotMatch(engine, /API 密钥: ['"]?\s*\+\s*API_SECRET/);
});

test("rollback and health verification are part of the template", () => {
  const rollback = read("rollback.sh");
  const health = read("health-check.sh");
  assert.match(rollback, /systemctl/);
  assert.match(rollback, /BACKUP_DIR/);
  assert.match(health, /127\.0\.0\.1:3911\/health/);
  assert.match(health, /curl -fsS/);
  assert.match(health, /systemctl is-active/);
  assert.match(health, /HEALTH_RETRIES/);
});
