import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";
import assert from "node:assert/strict";

import createLinuxCncTpModule from "../../../build/wasm/tp/linuxcnc_tp.js";

function verifyExpectedOutput(fixtureName, output, expectedText) {
  const expectedLines = expectedText.split("\n").filter(Boolean);

  for (const expectedLine of expectedLines) {
    assert.equal(
      output.includes(expectedLine),
      true,
      `${fixtureName}: ${expectedLine}`,
    );
  }
}

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const rootDir = resolve(__dirname, "../../..");
const wasmPath = resolve(rootDir, "build/wasm/tp/linuxcnc_tp.wasm");

const tp = await createLinuxCncTpModule({
  wasmBinary: readFileSync(wasmPath),
  print() {},
  printErr(message) {
    console.error(message);
  },
});

const resultPtr = tp._lctp_run_probe();
assert.notEqual(resultPtr, 0);
try {
  const output = tp.UTF8ToString(resultPtr);
  verifyExpectedOutput(
    "tp_wasm_probe",
    output,
    [
      "tp_default_queue_size=32",
      "tp_err_ok=0",
      "tc_linear=1",
      "tc_circular=2",
      "pose_xyz=1,2,3",
      "tp_create=0",
      "tp_set_cycle_time=0",
      "tp_set_pos=0",
      "tp_set_vmax=0",
      "tp_set_vlimit=0",
      "tp_set_amax=0",
      "tp_set_term_cond=0",
      "tp_add_line=0",
      "tp_cycle_rc=4",
      "tp_get_pos=0",
      "tp_done_after_line=1",
      "tp_queue_depth=0",
      "tp_final_pos=1,0,0",
      "tp_arc_create=0",
      "tp_add_circle=0",
      "tp_arc_cycle_rc=4",
      "tp_arc_get_pos=0",
      "tp_done_after_arc=1",
      "tp_arc_queue_depth=0",
      "tp_arc_final_pos_near_end=1",
      "tp_queue_create=0",
      "tp_queue_add_line1=0",
      "tp_queue_depth_after_line1=1",
      "tp_queue_add_line2=0",
      "tp_queue_depth_after_line2=2",
      "tp_queue_cycle_rc=4",
      "tp_queue_get_pos=0",
      "tp_done_after_queued_lines=1",
      "tp_queue_final_depth=0",
      "tp_queue_final_pos_near_end=1",
      "tp_queue_final_pos=1,1,0",
    ].join("\n"),
  );
} finally {
  tp._lctp_free_string(resultPtr);
}

console.log("tp_wasm_node_smoke=ok");
