import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";

const root = new URL("../", import.meta.url);

test("Map Page registers a provider-neutral reference-points slot and three station profiles", async () => {
  const pages = JSON.parse(await readFile(new URL("registry/pages.json", root), "utf8"));
  const profiles = JSON.parse(await readFile(new URL("registry/map-presentation-profiles.json", root), "utf8"));
  const mapPage = pages.templates.find((template) => template.id === "map");
  const stationProfiles = profiles.profiles.filter((profile) => profile.id.startsWith("map.reference.transport."));

  assert.ok(mapPage.slots.some((slot) => slot.id === "reference-points" && slot.kind === "entity-stream"));
  assert.deepEqual(
    stationProfiles.map((profile) => profile.id).sort(),
    [
      "map.reference.transport.metro.v1",
      "map.reference.transport.railway-station.v1",
      "map.reference.transport.terminal.v1",
    ],
  );
  assert.deepEqual(
    new Set(stationProfiles.flatMap((profile) => profile.semanticTypes)),
    new Set(["map.station", "map.terminal"]),
  );
  assert.ok(stationProfiles.every((profile) => profile.target.variant === "elevated-spike"));
});

test("existing layouts upgrade reference layers on read and renderer accepts their slot", async () => {
  const server = await readFile(new URL("server/catalog-server.mjs", root), "utf8");
  const renderer = await readFile(new URL("apps/catalog/src/CesiumMapRenderer.tsx", root), "utf8");
  const runtime = await readFile(new URL("apps/catalog/src/useMapReferenceRuntime.ts", root), "utf8");

  assert.match(server, /pageLayoutMatch\[1\] === "map" \? validateMapPageLayout\(stored\) : stored/);
  assert.match(server, /referenceLayers: structuredClone\(canonicalMapReferenceLayers\)/);
  assert.match(renderer, /binding\.slotId === "reference-points"/);
  assert.match(runtime, /\/api\/map-gateway\/api\/map\/reference-sources\/v1\/profiles\//);
  assert.match(runtime, /allowedAttributes = new Set\(\["name", "category", "network", "operator", "official_name", "local_name", "uic_ref", "wheelchair"\]\)/);
  assert.doesNotMatch(runtime, /credential|accessToken|providerEndpoint|rawPayload/);
});
