"use strict";
const assert = require("node:assert/strict");
const test = require("node:test");
const {
  createServer, loadMap, loadNodeMap, loadSubjectRegistry, loadSubjectAliasMap,
  resolveSubjectId, search, searchAll,
} = require("./server");

test("repository map exposes only the two current code-channel repositories", () => {
  const map = loadMap();
  const expectedCodes = ["REPO-012", "REPO-014"];
  assert.deepEqual(map.repositories.map(item => item.code), expectedCodes);
  assert.equal(new Set(map.repositories.map(item => item.code)).size, expectedCodes.length);
  for (const item of map.repositories) {
    assert.match(item.primary.url, /^https:\/\/guanghulab\.com\/code\//);
  }
  assert.equal(map.historical_repositories.length, 11);
  assert.ok(map.historical_repositories.every(item => item.state.includes("HISTORICAL")));
});

test("Chinese language-world query resolves the Fifth Domain primary", () => {
  const results = search(loadMap(), "光湖语言世界 第五域");
  assert.equal(results[0].code, "REPO-012");
  assert.equal(results[0].state, "CURRENT_FIFTH_DOMAIN_ENTRY");
});

test("Chenglu legacy identity does not resolve as a current repository", () => {
  const results = search(loadMap(), "澄路 常驻人格体 湖心频道");
  assert.equal(results.length, 0);
});

test("Kezhou and Guideng legacy identities do not resolve as current repositories", () => {
  assert.equal(search(loadMap(), "刻舟 湖心频道").length, 0);
  assert.equal(search(loadMap(), "归灯 每日心跳").length, 0);
});

test("server node map binds Zhuyuan routes to the domestic primary", () => {
  const map = loadNodeMap();
  assert.equal(map.map_id, "FD-NODE-MAP-001");
  assert.equal(map.default_node, "JD-FD-PRIMARY");
  const node = map.nodes.find(item => item.node_id === "JD-FD-PRIMARY");
  assert.ok(node.persona_systems.includes("ICE-P-ZY001"));
  const loop = map.persona_routes.find(item => item.route_id === "ZY-OPS-LOOP-001");
  assert.equal(loop.primary_node, "JD-FD-PRIMARY");
  assert.match(loop.path, /zhuyuan-persona-system/);
  const serialized = JSON.stringify(map);
  assert.doesNotMatch(serialized, /ssh-(?:rsa|ed25519)\s+[A-Za-z0-9+/]/i);
  assert.doesNotMatch(serialized, /"(?:password|token|private_key|ip)"\s*:/i);
  assert.doesNotMatch(serialized, /\b(?:\d{1,3}\.){3}\d{1,3}\b/);
});

test("Zhuyuan Chinese query returns the numbered operation loop", () => {
  const results = searchAll(loadMap(), loadNodeMap(), "铸渊 双向意识 思维逻辑链");
  assert.equal(results[0].kind, "persona_route");
  assert.equal(results[0].route_id, "ZY-OPS-LOOP-001");
});

test("legacy Zhuyuan ids canonicalize before navigation", () => {
  const aliases = loadSubjectAliasMap();
  for (const legacyId of ["ICE-GL-ZY001", "ICE-PZY-001"]) {
    const resolved = resolveSubjectId(aliases, legacyId);
    assert.equal(resolved.canonical_id, "ICE-P-ZY001");
    assert.equal(resolved.redirected, true);
    assert.equal(resolved.route_id, "FD-PERSONA-LOGIN-001");
  }
  assert.equal(resolveSubjectId(aliases, "ICE-P-ZY001").redirected, false);
});

test("human ids remain human and conflicted persona ids fail closed", () => {
  const aliases = loadSubjectAliasMap();
  assert.equal(resolveSubjectId(aliases, "ICE-GL∞").status, "NOT_FOUND_NO_GUESS");
  assert.equal(resolveSubjectId(aliases, "ICE-PCA-001").status, "CONFLICT_REJECTED");
});

test("searching the old id returns the canonical subject", () => {
  const results = searchAll(loadMap(), loadNodeMap(), "ICE-GL-ZY001", loadSubjectRegistry());
  const subject = results.find(item => item.kind === "subject");
  assert.equal(subject.id, "ICE-P-ZY001");
  assert.ok(subject.legacy_ids.includes("ICE-GL-ZY001"));
});

test("public endpoints are read-only and expose CORS", async () => {
  const server = createServer();
  await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
  const base = `http://127.0.0.1:${server.address().port}`;
  try {
    const response = await fetch(`${base}/v1/resolve?id=REPO-004`);
    assert.equal(response.status, 404);
    assert.equal(response.headers.get("access-control-allow-origin"), "*");
    assert.equal((await response.json()).error, "route_not_found");
    const currentRepository = await fetch(`${base}/v1/resolve?id=REPO-014`);
    assert.equal(currentRepository.status, 200);
    assert.equal((await currentRepository.json()).slug, "hololake-system-architecture");
    const nodeResponse = await fetch(`${base}/v1/resolve?id=JD-FD-PRIMARY`);
    assert.equal(nodeResponse.status, 200);
    assert.equal((await nodeResponse.json()).node_id, "JD-FD-PRIMARY");
    const loopResponse = await fetch(`${base}/v1/resolve?id=ZY-OPS-LOOP-001`);
    assert.equal(loopResponse.status, 200);
    assert.equal((await loopResponse.json()).persona_system, "ICE-P-ZY001");
    const legacyResponse = await fetch(`${base}/v1/resolve?id=ICE-GL-ZY001`);
    assert.equal(legacyResponse.status, 200);
    const legacyResolution = await legacyResponse.json();
    assert.equal(legacyResolution.canonical_id, "ICE-P-ZY001");
    assert.equal(legacyResolution.redirected, true);
    assert.equal(legacyResolution.subject.subject_kind, "persona_system");
    const canonicalResponse = await fetch(`${base}/v1/resolve?id=ICE-P-ZY001`);
    assert.equal((await canonicalResponse.json()).redirected, false);
    const humanResponse = await fetch(`${base}/v1/resolve?id=${encodeURIComponent("ICE-GL∞")}`);
    const humanResolution = await humanResponse.json();
    assert.equal(humanResponse.status, 200);
    assert.equal(humanResolution.subject_kind, "human");
    assert.equal(humanResolution.canonical_id, "ICE-GL∞");
    assert.equal((await fetch(`${base}/v1/resolve?id=ICE-PCA-001`)).status, 409);
    const manifestResponse = await fetch(`${base}/well-known`);
    const manifest = await manifestResponse.json();
    assert.equal(manifest.write_authorization.request_credential_required, false);
    assert.match(manifest.write_authorization.create_workorder, /\/authz\/api\/public\/workorders$/);
    assert.equal((await fetch(`${base}/v1/search`, { method: "POST" })).status, 405);
  } finally { await new Promise(resolve => server.close(resolve)); }
});
