#!/usr/bin/env node
// Runtime unit tests for siteasy live-mode path containment and design-system
// slug sanitisation. Pure Node standard library. Run: node tests/unit.mjs
import { resolveInRoot, looksGenerated } from "../skills/siteasy/scripts/live-core.mjs";
import { resolve } from "node:path";

let failures = 0;
function ok(name, cond) {
  if (cond) console.log(`  ✅  ${name}`);
  else { console.error(`  ❌  ${name}`); failures++; }
}

console.log("\n── resolveInRoot: stays inside the project root ──");
const root = resolve("/proj");
ok("plain file resolves under root", resolveInRoot(root, "a.txt") === resolve(root, "a.txt"));
ok("nested file resolves under root", resolveInRoot(root, "sub/a.txt") === resolve(root, "sub/a.txt"));
ok("inner ../ that stays inside is allowed", resolveInRoot(root, "sub/../a.txt") === resolve(root, "a.txt"));

console.log("\n── resolveInRoot: rejects escapes ──");
ok("../ escape rejected", resolveInRoot(root, "../escape.txt") === null);
ok("deep ../ escape rejected", resolveInRoot(root, "a/../../escape.txt") === null);
ok("absolute path rejected", resolveInRoot(root, "/etc/passwd") === null);
ok("empty string rejected", resolveInRoot(root, "") === null);
ok("non-string rejected", resolveInRoot(root, null) === null);

console.log("\n── looksGenerated: detects generated-file markers ──");
ok("@generated detected", looksGenerated("// @generated by tool\nbody") === true);
ok("DO NOT EDIT detected", looksGenerated("/* DO NOT EDIT */\nbody") === true);
ok("plain content not flagged", looksGenerated("hello world") === false);

console.log("\n" + "═".repeat(50));
if (failures > 0) {
  console.error(`❌  unit tests FAILED: ${failures} failure(s).`);
  process.exit(1);
}
console.log("✅  unit tests passed.");
process.exit(0);
