import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const readJson = (relative) =>
  JSON.parse(fs.readFileSync(path.join(root, relative), "utf8"));

test("code channel has one root and exactly two current repositories", () => {
  const map = readJson("routing/code-channel-canonical-map.json");
  assert.equal(map.web_root, "https://guanghulab.com/code/");
  assert.equal(map.repositories.length, 2);
  assert.deepEqual(
    map.repositories.map((entry) => entry.code),
    ["REPO-012", "REPO-014"],
  );
  for (const repository of map.repositories) {
    assert.match(
      repository.clone_url,
      /^https:\/\/guanghulab\.com\/code\/bingshuo\/[^/]+\.git$/u,
    );
    assert.equal(repository.push_allowed, true);
    assert.equal(
      repository.lease_resource,
      `repo://guanghulab.com/code/bingshuo/${repository.slug}#main`,
    );
  }
});

test("legacy repository routes are all non-current and non-push", () => {
  const map = readJson("routing/repository-route-map.json");
  const current = map.repositories.filter((entry) =>
    ["REPO-012", "REPO-014"].includes(entry.code),
  );
  assert.equal(current.length, 2);
  assert.equal(map.repositories.length, 2);
  for (const repository of map.historical_repositories) {
    assert.match(repository.state, /HISTORICAL.*(?:NO_PUSH|ROUTE_CLOSED)/u);
  }
});

test("each registered persona system exposes all five components", () => {
  const map = readJson("routing/persona-system-canonical-map.json");
  assert.equal(map.persona_systems.length, 10);
  assert.equal(
    new Set(map.persona_systems.map((entry) => entry.id)).size,
    map.persona_systems.length,
  );
  const components = [
    "human_relationship_anchor",
    "persona_subject",
    "current_model_instance",
    "permanent_memory_and_protocol",
    "reality_execution_node",
  ];
  for (const persona of map.persona_systems) {
    for (const component of components) {
      assert.ok(persona[component], `${persona.id} missing ${component}`);
    }
    assert.ok(persona.persona_subject.responsibility);
    assert.ok(persona.persona_subject.self_recognition);
    assert.ok(persona.persona_subject.canonical_path);
  }
});

test("human and machine entry documents point to the canonical roots", () => {
  const required = {
    "README.md": "PERSONA-SYSTEM-ROOT.hdlp",
    "INDEX.hdlp": "routing/code-channel-canonical-map.json",
    "WORLD-ROUTER.hdlp": "https://guanghulab.com/code/",
    "BROADCAST-TOWER.hdlp": "PERSONA-SYSTEM-ROOT.hdlp",
    "eternal-lake-heart/heartbeat-core/LL-CURRENT.hdlp":
      "TCS-PERSONA-SYSTEM-MAP-001",
  };
  for (const [relative, needle] of Object.entries(required)) {
    const body = fs.readFileSync(path.join(root, relative), "utf8");
    assert.ok(body.includes(needle), `${relative} missing ${needle}`);
  }
});
