/// <reference lib="webworker" />
import {
  Pcre2EngineAdapter,
  PCRE2_ENGINE_VERSION,
} from "../regex/execution/adapters/pcre2/Pcre2EngineAdapter";
import { importPcre2ModuleFactory } from "../regex/execution/adapters/pcre2/pcre2-module";
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<Pcre2EngineAdapter> | 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<Pcre2EngineAdapter> {
  const moduleUrl = new URL("engines/pcre2/pcre2.mjs", applicationRoot());
  const factory = await importPcre2ModuleFactory(moduleUrl);
  const module = await factory({
    locateFile: (name) => new URL(name, moduleUrl).href,
    print: () => undefined,
    printErr: (line) => console.warn(`PCRE2 ${line}`),
  });
  const adapter = new Pcre2EngineAdapter(
    module,
    `WebAssembly · ${scope.navigator.userAgent}`,
  );
  const info = await adapter.load();
  if (info.engineVersion !== PCRE2_ENGINE_VERSION) {
    throw new Error(
      "Loaded PCRE2 runtime identity does not match the adapter.",
    );
  }
  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);
};
