/**
 * PR-B Architecture Guard — Unified Test
 * Runs all 6 guards as node:test sub-tests.
 * 
 * Run: node --test test/architecture/guard.test.mjs
 */

import { describe, it } from "node:test";
import assert from "node:assert";
import { spawnSync } from "node:child_process";
import { join } from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = join(fileURLToPath(import.meta.url), "..", "..", "..");
const SCRIPTS_DIR = join(__dirname, "scripts");

function runGuard(name, script, expectExit0 = true) {
  const result = spawnSync("node", [script], {
    cwd: __dirname,
    encoding: "utf8",
    timeout: 30000,
    maxBuffer: 1024 * 1024,
  });
  
  const output = result.stdout + result.stderr;
  
  return {
    name,
    exitCode: result.status,
    signal: result.signal,
    output: output.slice(-500), // Keep last 500 chars for report
    passed: result.status === 0,
  };
}

describe("PR-B: Architecture Guard", () => {
  it("Guard-01: Memory backend count ≤ allowed", () => {
    const r = runGuard("Memory Backend", join(SCRIPTS_DIR, "guard-memory-backend.mjs"));
    console.log(r.output);
    assert.equal(r.exitCode, 0, `Guard 1 failed (exit ${r.exitCode})`);
  });

  it("Guard-02: Runtime core count ≤ 3", () => {
    const r = runGuard("Runtime Core", join(SCRIPTS_DIR, "guard-runtime-core.mjs"));
    console.log(r.output);
    assert.equal(r.exitCode, 0, `Guard 2 failed (exit ${r.exitCode})`);
  });

  it("Guard-03: Tool path inventory (soft)", () => {
    const r = runGuard("Tool Path", join(SCRIPTS_DIR, "guard-tool-path.mjs"));
    console.log(r.output);
    // Soft guard — informational only
    assert.ok(r.exitCode === 0 || r.exitCode === null, 
      `Guard 3 unexpected error (exit ${r.exitCode})`);
  });

  it("Guard-04: MEMORY.md direct write paths unchanged", () => {
    const r = runGuard("MEMORY.md Write", join(SCRIPTS_DIR, "guard-memory-write.mjs"));
    console.log(r.output);
    assert.equal(r.exitCode, 0, `Guard 4 failed (exit ${r.exitCode})`);
  });

  it("Guard-05: Tool trace coverage (soft)", () => {
    const r = runGuard("Tool Trace", join(SCRIPTS_DIR, "guard-tool-trace.mjs"));
    console.log(r.output);
    // Soft guard — informational only
    assert.ok(r.exitCode === 0 || r.exitCode === null,
      `Guard 5 unexpected error (exit ${r.exitCode})`);
  });

  it("Guard-06: Dreaming phase count ≤ 3", () => {
    const r = runGuard("Dreaming Phase", join(SCRIPTS_DIR, "guard-dreaming-phase.mjs"));
    console.log(r.output);
    assert.equal(r.exitCode, 0, `Guard 6 failed (exit ${r.exitCode})`);
  });
});
