import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import test from "node:test";

import makeRerunRuntime from "../vendor/rerun-web-viewer-0.34.1/re_viewer.nodedc.js";

const root = resolve(import.meta.dirname, "..");
const packageRoot = resolve(root, "node_modules/@rerun-io/web-viewer");
const vendorRoot = resolve(root, "vendor/rerun-web-viewer-0.34.1");

const sha256 = (path) =>
  createHash("sha256").update(readFileSync(path)).digest("hex");

test("NODE.DC Rerun runtime is the audited 0.34.1 spatial camera build", () => {
  const manifest = JSON.parse(readFileSync(resolve(packageRoot, "package.json"), "utf8"));
  assert.equal(manifest.version, "0.34.1");

  const expectedWasm = "ffe7543d28bb3394f289f6299de43d038767eef83d781c2b7f8f5683308a0469";
  const expectedGlue = "0f7b76c9f24cbd8437021b5d37499894aeadc586183e422ebc82ef556d7b8339";

  assert.equal(sha256(resolve(vendorRoot, "re_viewer_bg.nodedc.wasm")), expectedWasm);
  assert.equal(sha256(resolve(vendorRoot, "re_viewer.nodedc.js")), expectedGlue);
  assert.equal(sha256(resolve(packageRoot, "re_viewer_bg.wasm")), expectedWasm);
  assert.equal(sha256(resolve(packageRoot, "re_viewer.js")), expectedGlue);
});

test("custom JavaScript glue references only exports present in its paired WASM", () => {
  const wasmPath = resolve(vendorRoot, "re_viewer_bg.nodedc.wasm");
  const gluePath = resolve(vendorRoot, "re_viewer.nodedc.js");
  const module = new WebAssembly.Module(readFileSync(wasmPath));
  const exports = new Set(WebAssembly.Module.exports(module).map(({ name }) => name));
  const imports = WebAssembly.Module.imports(module);
  const glue = readFileSync(gluePath, "utf8");
  const referencedExports = new Set(
    [...glue.matchAll(/\bwasm\.([A-Za-z_$][\w$]*)/g)].map((match) => match[1]),
  );
  const missingExports = [...referencedExports].filter((name) => !exports.has(name));

  assert.equal(imports.length, 927);
  assert.equal(exports.size, 79);
  assert.deepEqual(missingExports, []);
  assert.match(glue, /export default function\(\)/);
  assert.match(glue, /if \(!wasm\) return;/);
});

test("custom Rerun WASM initializes and grows its externref table", () => {
  const runtime = makeRerunRuntime();
  runtime.initSync({
    module: readFileSync(resolve(vendorRoot, "re_viewer_bg.nodedc.wasm")),
  });

  assert.equal(typeof runtime.WebHandle, "function");
  runtime.deinit();
});

test("source patch carries pointer navigation, persistent follow, and camera continuity tests", () => {
  const patch = readFileSync(resolve(vendorRoot, "NODEDC_ZOOM_TO_CURSOR.patch"), "utf8");

  assert.match(patch, /fn pointer_ray_direction/);
  assert.match(patch, /fn zoom_orbit_towards_pointer/);
  assert.match(patch, /near_limit_hands_excess_zoom_to_cursor_directed_dolly/);
  assert.match(patch, /crossing_near_limit_preserves_unconsumed_scene_scaled_zoom/);
  assert.match(patch, /remaining_zoom_factor\.ln\(\) \* self\.speed/);
  assert.match(patch, /off_center_pointer_stays_on_the_same_view_ray/);
  assert.match(patch, /fn rotate_radians_around_anchor/);
  assert.match(patch, /orbit_drag_anchor/);
  assert.match(patch, /minimum_orbital_navigation_speed/);
  assert.match(patch, /orbital_rotation_keeps_selected_anchor_on_the_same_view_ray/);
  assert.match(patch, /orbital_navigation_speed_floor_tracks_scene_scale/);
  assert.match(patch, /NODEDC_PERSISTENT_ORBIT_TRACKING_ENTITY/);
  assert.match(patch, /nodedc_rig_orbit_tracking_is_persistent/);
  assert.match(patch, /restore_persistent_orbit_eye_after_blueprint_update/);
  assert.match(
    patch,
    /persistent_rig_follow_restores_the_last_rendered_eye_after_blueprint_update/,
  );
  assert.match(patch, /explicit_blueprint_pose_is_not_replaced_by_the_previous_eye/);
  assert.match(patch, /previous_picking_result/);
});
