import { createRuntime } from "./runtime";
import type { InferenceRequest, InferenceResult } from "../shared/types";

const OFFSCREEN_URL = "offscreen.html";

async function ensureOffscreen(): Promise<void> {
  const contexts = await chrome.runtime.getContexts?.({ contextTypes: ["OFFSCREEN_DOCUMENT"] as never });
  if (!contexts || contexts.length === 0) await chrome.offscreen.createDocument({ url: OFFSCREEN_URL, reasons: ["WORKERS"] as never, justification: "Run the local toxicity classifier in a durable worker." });
}

async function runInOffscreen(requests: InferenceRequest[]): Promise<InferenceResult[]> {
  await ensureOffscreen();
  const response = await chrome.runtime.sendMessage({ type: "OFFSCREEN_INFER", requests });
  if (response?.error) throw new Error(response.error);
  return response?.results ?? [];
}

createRuntime(runInOffscreen);
