/* SDARC synthetic engine runner. The verified matching Go runtime precedes
 * this source in a fresh worker. No database, account or credentials are used.
 * Copyright (c) 2026 Neuroclusive. You may download, inspect, modify and run
 * this wrapper for testing and review. Other source licenses are unchanged. */

let report;
let receive;
if (typeof process !== "undefined" && process.versions?.node) {
  const { parentPort } = await import("node:worker_threads");
  report = (message) => parentPort.postMessage(message);
  receive = (handler) => parentPort.once("message", handler);
} else {
  report = (message) => self.postMessage(message);
  receive = (handler) =>
    self.addEventListener("message", (event) => handler(event.data), {
      once: true,
    });
}

receive(async ({ wasmBytes }) => {
  let finished = false;
  const fail = (error) => {
    if (finished) return;
    finished = true;
    report({
      type: "error",
      error: error instanceof Error ? error.message : String(error),
    });
  };
  try {
    if (
      !(wasmBytes instanceof ArrayBuffer) ||
      typeof globalThis.Go !== "function"
    ) {
      throw new Error(
        "Verified WASM or its matching Go runtime is unavailable",
      );
    }
    const go = new globalThis.Go();
    go.argv = ["sdarc-public-lifecycle"];
    go.env = {};
    go.exit = (code) => {
      if (code !== 0) fail(new Error(`SDARC engine exited with code ${code}`));
    };
    const { instance } = await WebAssembly.instantiate(
      wasmBytes,
      go.importObject,
    );
    Promise.resolve(go.run(instance)).catch(fail);
    const deadline = Date.now() + 20_000;
    while (typeof globalThis.sdarcLifecycleRun !== "function") {
      if (finished) return;
      if (Date.now() >= deadline)
        throw new Error(
          "SDARC engine did not register its lifecycle entry point",
        );
      await new Promise((resolve) => setTimeout(resolve, 10));
    }
    // RSA import, encrypted processing and lifecycle commands all run inside Go.
    // The wrapper has no built-in success rows or alternative demonstration.
    const serialized = globalThis.sdarcLifecycleRun();
    if (typeof serialized !== "string" || serialized.length > 256_000) {
      throw new Error("SDARC engine returned an invalid result");
    }
    const result = JSON.parse(serialized);
    finished = true;
    report({ type: "result", result });
  } catch (error) {
    fail(error);
  }
});
