/// <reference lib="webworker" />
import {
  RUST_ENGINE_VERSION,
  RustEngineAdapter,
} from "../regex/execution/adapters/rust/RustEngineAdapter";
import {
  RustWasmBridge,
  importRustRegexWasmModule,
} from "../regex/execution/adapters/rust/RustWasmBridge";
import {
  WORKER_PROTOCOL_VERSION,
  workerError,
  type EngineWorkerOperation,
  type EngineWorkerResult,
  type WorkerRequest,
  type WorkerResponse,
} from "../regex/execution/worker-protocol";

const scope = self as DedicatedWorkerGlobalScope;
let adapterPromise: Promise<RustEngineAdapter> | undefined;

function applicationRoot(): URL {
  const worker = new URL(scope.location.href);
  const assets = worker.pathname.lastIndexOf("/assets/");
  if (assets >= 0) {
    worker.pathname = worker.pathname.slice(0, assets + 1);
  } else {
    const sourceWorker = worker.pathname.lastIndexOf("/src/workers/");
    worker.pathname =
      sourceWorker >= 0 ? worker.pathname.slice(0, sourceWorker + 1) : "/";
  }
  worker.search = "";
  worker.hash = "";
  return worker;
}

async function loadAdapter(): Promise<RustEngineAdapter> {
  const engineRoot = new URL("engines/rust/", applicationRoot());
  const module = await importRustRegexWasmModule(
    new URL("rust-regex.mjs", engineRoot),
    new URL("rust-regex_bg.wasm", engineRoot),
  );
  const adapter = new RustEngineAdapter(
    new RustWasmBridge(module),
    scope.navigator.userAgent,
  );
  const info = await adapter.load();
  if (info.engineVersion !== RUST_ENGINE_VERSION) {
    throw new Error("Loaded Rust regex runtime identity does not match.");
  }
  return adapter;
}

scope.onmessage = async (
  event: MessageEvent<WorkerRequest<EngineWorkerOperation>>,
) => {
  const request = event.data;
  if (request.protocolVersion !== WORKER_PROTOCOL_VERSION) return;
  let response: WorkerResponse<EngineWorkerResult>;
  try {
    adapterPromise ??= loadAdapter();
    const adapter = await adapterPromise;
    const payload: EngineWorkerResult =
      request.payload.kind === "load"
        ? { kind: "load", info: await adapter.load() }
        : request.payload.kind === "execute"
          ? {
              kind: "execute",
              result: await adapter.execute(request.payload.request),
            }
          : {
              kind: "replace",
              result: await adapter.replace(request.payload.request),
            };
    response = {
      protocolVersion: WORKER_PROTOCOL_VERSION,
      requestId: request.requestId,
      generation: request.generation,
      ok: true,
      payload,
    };
  } catch (error) {
    response = {
      protocolVersion: WORKER_PROTOCOL_VERSION,
      requestId: request.requestId,
      generation: request.generation,
      ok: false,
      error: workerError(error),
    };
  }
  scope.postMessage(response);
};
