/// <reference lib="webworker" />
import {
  PHP_ENGINE_VERSION,
  PhpEngineAdapter,
} from "../regex/execution/adapters/php/PhpEngineAdapter";
import {
  PHP,
  loadPHPRuntime,
  type PhpLoaderModule,
} from "../regex/execution/adapters/php/php-runtime";
import { PhpWasmBridge } from "../regex/execution/adapters/php/PhpWasmBridge";
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<PhpEngineAdapter> | 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 importLoader(url: URL): Promise<PhpLoaderModule> {
  const imported: unknown = await import(/* @vite-ignore */ url.href);
  if (
    typeof imported !== "object" ||
    imported === null ||
    typeof (imported as Partial<PhpLoaderModule>).init !== "function" ||
    typeof (imported as Partial<PhpLoaderModule>).dependencyFilename !==
      "string" ||
    (imported as Partial<PhpLoaderModule>).dependenciesTotalSize !== 21_019_221
  ) {
    throw new Error("The PHP Asyncify loader module is malformed.");
  }
  return imported as PhpLoaderModule;
}

async function loadAdapter(): Promise<PhpEngineAdapter> {
  const engineRoot = new URL("engines/php/", applicationRoot());
  const loader = await importLoader(new URL("php-loader.mjs", engineRoot));
  const wasmUrl = new URL("php.wasm", engineRoot);
  const runtimeId = await loadPHPRuntime(loader, {
    phpWasmAsyncMode: "asyncify",
    locateFile: (requested: string) =>
      requested.endsWith(".wasm") ? wasmUrl.href : requested,
    debug: false,
    print: () => undefined,
    printErr: () => undefined,
  });
  const bridge = new PhpWasmBridge(new PHP(runtimeId));
  const adapter = new PhpEngineAdapter(bridge, scope.navigator.userAgent);
  const info = await adapter.load();
  if (info.engineVersion !== PHP_ENGINE_VERSION) {
    throw new Error("Loaded PHP preg 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);
};
