/// <reference lib="webworker" />
import {
  PythonEngineAdapter,
  PYODIDE_ENGINE_VERSION,
  PYTHON_ENGINE_VERSION,
} from "../regex/execution/adapters/python/PythonEngineAdapter";
import { importPyodideModule } from "../regex/execution/adapters/python/python-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<PythonEngineAdapter> | 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<PythonEngineAdapter> {
  const moduleUrl = new URL("engines/python/pyodide.mjs", applicationRoot());
  const imported = await importPyodideModule(moduleUrl);
  if (imported.version !== PYODIDE_ENGINE_VERSION) {
    throw new Error(
      "Loaded Pyodide module identity does not match the adapter.",
    );
  }
  const runtime = await imported.loadPyodide({
    indexURL: new URL(".", moduleUrl).href,
    stdout: () => undefined,
    stderr: (line) => console.warn(`Python ${line}`),
  });
  const adapter = new PythonEngineAdapter(runtime, scope.navigator.userAgent);
  const info = await adapter.load();
  if (info.engineVersion !== PYTHON_ENGINE_VERSION) {
    throw new Error(
      "Loaded Python 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);
};
