import { readFile } from "node:fs/promises";
import { buildDir, rootDir } from "#og-image-virtual/build-dir.mjs";
import { getRequestURL } from "h3";
import { useRuntimeConfig } from "nitropack/runtime";
import { join } from "pathe";
import { withBase } from "ufo";
let fontUrlMapping;
async function loadFontUrlMapping() {
  if (fontUrlMapping)
    return fontUrlMapping;
  const content = await readFile(join(buildDir, "cache", "og-image", "font-urls.json"), "utf-8").catch(() => null);
  fontUrlMapping = content ? JSON.parse(content) : {};
  return fontUrlMapping;
}
export async function resolve(event, font) {
  const path = font.src || font.localPath;
  if (font.absolutePath) {
    const data = await readFile(font.absolutePath).catch(() => null);
    if (data?.length)
      return data;
  }
  if (import.meta.prerender) {
    if (path.startsWith("/_og-static-fonts/")) {
      const filename2 = path.slice("/_og-static-fonts/".length);
      const cached = await readFile(join(buildDir, "cache", "og-image", "fonts-ttf", filename2)).catch(() => null) || await readFile(join(rootDir, ".output", "public", "_og-static-fonts", filename2)).catch(() => null);
      if (cached?.length)
        return cached;
    }
    if (path.startsWith("/_fonts/")) {
      const filename2 = path.slice("/_fonts/".length);
      const cached = await readFile(join(rootDir, ".output", "public", "_fonts", filename2)).catch(() => null);
      if (cached?.length)
        return cached;
      const mapping = await loadFontUrlMapping();
      if (mapping[filename2]) {
        const res = await fetch(mapping[filename2]).catch(() => null);
        if (res?.ok)
          return Buffer.from(await res.arrayBuffer());
      }
      throw new Error(`Font ${filename2} not found in mapping or cache`);
    }
    const filename = path.slice(1);
    const data = await readFile(join(rootDir, "public", filename)).catch(() => null) || await readFile(join(rootDir, ".output", "public", filename)).catch(() => null);
    if (data?.length)
      return data;
  }
  if (path.startsWith("/_og-static-fonts/")) {
    const filename = path.slice("/_og-static-fonts/".length);
    const cached = await readFile(join(buildDir, "cache", "og-image", "fonts-ttf", filename)).catch(() => null);
    if (cached?.length)
      return cached;
  }
  if (import.meta.dev && path.startsWith("/_fonts/")) {
    const filename = path.slice("/_fonts/".length);
    const mapping = await loadFontUrlMapping();
    if (mapping[filename]) {
      const res = await fetch(mapping[filename]).catch(() => null);
      if (res?.ok)
        return Buffer.from(await res.arrayBuffer());
    }
  }
  if (import.meta.dev) {
    const filename = path.slice(1);
    const data = await readFile(join(rootDir, "public", filename)).catch(() => null);
    if (data?.length)
      return data;
  }
  const { app } = useRuntimeConfig();
  if (import.meta.dev) {
    const reqUrl = getRequestURL(event);
    const origin = `${reqUrl.protocol}//${reqUrl.host}`;
    const url = new URL(withBase(path, app.baseURL), origin).href;
    const res = await fetch(url).catch(() => null);
    if (res?.ok) {
      return Buffer.from(await res.arrayBuffer());
    }
  }
  const fullPath = withBase(path, app.baseURL);
  const arrayBuffer = await event.$fetch(fullPath, {
    responseType: "arrayBuffer"
  });
  return Buffer.from(arrayBuffer);
}
