"use strict";

const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { parseResource, safeRelative, validateManifest, validateUnit, provision } = require("./architecture-provision-broker");

const commit = "d".repeat(40);
const requestId = "GLS-0231-JD-LAN-01-INITIAL-PROVISION-20260720";

function manifest() {
  return {
    schema: "guanghu.architecture-provision-request/v1", request_id: requestId, target_node: "JD-FD-PRIMARY", status: "ARCHITECTURE_PACKAGE_READY · INITIAL_PROVISION_PENDING",
    module: { unit: "example.service", run_user: "guanghu" }, initial_provision: { kind: "new-architecture-unit" },
    source_paths: ["server-tools/example/server.js", "server-tools/example/example.service"],
    runtime_check: { url: "http://127.0.0.1:3924/health", expected: { ok: true, mode: "read-only" } },
  };
}

test("resource and manifest are immutable and path constrained", () => {
  assert.deepEqual(parseResource(`${requestId}@${commit}`), { requestId, commit });
  assert.equal(parseResource(`${requestId}@main`), null);
  assert.equal(safeRelative("server-tools/example/server.js"), true);
  assert.equal(safeRelative("../etc/passwd"), false);
  assert.equal(validateManifest(manifest(), { requestId, commit }).unit, "example.service");
});

test("unit requires non-root systemd hardening and release placeholder", () => {
  const unit = "[Service]\nUser=guanghu\nGroup=guanghu\nNoNewPrivileges=true\nPrivateTmp=true\nProtectSystem=strict\nProtectHome=true\nExecStart=/usr/bin/node __RELEASE_ROOT__/server.js\n";
  assert.equal(validateUnit(unit), unit);
  assert.throws(() => validateUnit(unit.replace("User=guanghu", "User=root")), /dedicated_service_user_required/);
  assert.throws(() => validateUnit(`${unit}EnvironmentFile=/etc/shadow\n`), /environment_file_not_declared/);
  assert.throws(() => validateUnit(unit.replace("__RELEASE_ROOT__", "/tmp/live")), /release_root_placeholder_required/);
});

test("unit permits a declared persona user, shared secret and state directory", () => {
  const unit = "[Service]\nUser=kezhou\nGroup=kezhou\nNoNewPrivileges=yes\nPrivateTmp=yes\nProtectSystem=strict\nProtectHome=yes\nEnvironmentFile=-/etc/guanghu/persona-secrets/shared-deepseek.env\nReadWritePaths=/var/lib/guanghu/personas/kezhou\nReadOnlyPaths=__RELEASE_ROOT__\nExecStart=__RELEASE_ROOT__/run.sh\n";
  const policy = { environment_files: ["/etc/guanghu/persona-secrets/shared-deepseek.env"], writable_paths: ["/var/lib/guanghu/personas/kezhou"], read_only_paths: [] };
  assert.equal(validateUnit(unit, "kezhou", policy), unit);
  assert.throws(() => validateUnit(unit.replace("shared-deepseek.env", "../../shadow"), "kezhou", policy), /environment_file_not_declared/);
  assert.throws(() => validateUnit(unit.replace("/var/lib/guanghu/personas/kezhou", "/opt/guanghu/personas/kezhou"), "kezhou", policy), /writable_path_not_declared/);
  assert.throws(() => validateUnit(unit.replaceAll("kezhou", "root"), "root", policy), /dedicated_service_user_required/);
});

test("provision copies only declared files and verifies loopback health", async () => {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "architecture-provision-"));
  const repoDir = path.join(root, "repo");
  const releasesDir = path.join(root, "releases");
  const unitDir = path.join(root, "units");
  const receiptsDir = path.join(root, "receipts");
  fs.mkdirSync(path.join(repoDir, "deployment", "requests"), { recursive: true });
  fs.mkdirSync(path.join(repoDir, "server-tools", "example"), { recursive: true });
  fs.writeFileSync(path.join(repoDir, "deployment", "requests", `${requestId}.json`), JSON.stringify(manifest()));
  fs.writeFileSync(path.join(repoDir, "server-tools", "example", "server.js"), "module.exports = {};\n");
  fs.writeFileSync(path.join(repoDir, "server-tools", "example", "example.service"), "[Service]\nUser=guanghu\nGroup=guanghu\nNoNewPrivileges=true\nPrivateTmp=true\nProtectSystem=strict\nProtectHome=true\nExecStart=/usr/bin/node __RELEASE_ROOT__/server-tools/example/server.js\n");
  const commands = [];
  let healthChecks = 0;
  try {
    const result = await provision({ target: "JD-FD-PRIMARY", action: "provision-approved-architecture", resource: `${requestId}@${commit}` }, {
      repoDir, releasesDir, unitDir, receiptsDir,
      run: async (file, args) => { commands.push([file, args]); return { stdout: args.includes("rev-parse") ? `${commit}\n` : "" }; },
      getJson: async () => {
        healthChecks += 1;
        if (healthChecks === 1) throw new Error("connection_refused_during_startup");
        return { ok: true, mode: "read-only" };
      },
      healthDelayMs: 0,
    });
    assert.equal(result.ok, true);
    assert.equal(fs.existsSync(path.join(releasesDir, commit, "server-tools", "example", "server.js")), true);
    assert.match(fs.readFileSync(path.join(unitDir, "example.service"), "utf8"), new RegExp(commit));
    assert.equal(commands.some(([, args]) => args.includes("enable") && args.includes("--now")), true);
    assert.equal(healthChecks, 2);
  } finally { fs.rmSync(root, { recursive: true, force: true }); }
});
