import { componentNames } from "#build/nuxt-og-image/components.mjs";
import { resolveUnrefHeadInput } from "@unhead/vue";
import { defu } from "defu";
import { stringify } from "devalue";
import { useHead, useRuntimeConfig } from "nuxt/app";
import { joinURL, withQuery } from "ufo";
import { logger } from "../logger.js";
import { buildOgImageUrl, generateMeta, separateProps } from "../shared.js";
const RE_RENDERER_SUFFIX = /(Satori|Browser|Takumi)$/;
export function setHeadOgImagePrebuilt(input) {
  if (import.meta.client) {
    return;
  }
  const url = input.url;
  if (!url)
    return;
  const meta = generateMeta(url, input);
  useHead({ meta }, { tagPriority: "high" });
}
export function createOgImageMeta(src, input, ssrContext) {
  if (import.meta.client) {
    return;
  }
  const { defaults } = useOgImageRuntimeConfig();
  const resolvedOptions = separateProps(defu(input, defaults));
  resolvedOptions.key = resolvedOptions.key || "og";
  const payloads = ssrContext._ogImagePayloads || [];
  const currentPayloadIdx = payloads.findIndex(([k]) => k === resolvedOptions.key);
  const _input = separateProps(defu(input, currentPayloadIdx >= 0 ? payloads[currentPayloadIdx][1] : {}));
  let url = src || input.url || resolvedOptions.url;
  if (!url)
    return;
  if (input._query && Object.keys(input._query).length && url)
    url = withQuery(url, { _query: input._query });
  const meta = generateMeta(url, resolvedOptions);
  if (currentPayloadIdx === -1) {
    payloads.push([resolvedOptions.key, _input, meta]);
  } else {
    payloads[currentPayloadIdx] = [resolvedOptions.key, _input, meta];
  }
  ssrContext._ogImageInstance?.dispose();
  ssrContext._ogImageInstance = useHead({
    meta() {
      const finalPayload = ssrContext._ogImagePayloads || [];
      return finalPayload.flatMap(([_, __, meta2]) => meta2);
    }
  }, {
    processTemplateParams: true,
    tagPriority: 35
  });
  if (import.meta.dev || import.meta.prerender) {
    ssrContext._ogImageDevtoolsInstance?.dispose();
    ssrContext._ogImageDevtoolsInstance = useHead({
      script: [{
        id: "nuxt-og-image-options",
        type: "application/json",
        processTemplateParams: true,
        innerHTML: () => {
          const devtoolsPayload = (ssrContext._ogImagePayloads || []).map(([key, options]) => {
            const payload = resolveUnrefHeadInput(options);
            if (payload.props && typeof payload.props.title === "undefined")
              payload.props.title = "%s";
            if (typeof payload.component === "string") {
              payload.component = resolveComponentName(payload.component);
            } else if (payload.component) {
              if (import.meta.dev)
                logger.warn(`defineOgImage() received a non-string component value (${typeof payload.component}). Pass the component name as a plain string.`);
              delete payload.component;
            }
            payload.key = key;
            delete payload.url;
            if (payload._query && Object.keys(payload._query).length === 0) {
              delete payload._query;
            }
            if (payload.props && typeof payload.props === "object" && Object.keys(payload.props).length === 0) {
              delete payload.props;
            }
            const ALWAYS_INCLUDE = /* @__PURE__ */ new Set(["component", "_hash", "key", "fonts"]);
            const final = {};
            for (const k in payload) {
              if (payload[k] === "")
                continue;
              if (ALWAYS_INCLUDE.has(k) || payload[k] !== defaults[k]) {
                final[k] = payload[k];
              }
            }
            return final;
          });
          return stringify(devtoolsPayload);
        },
        tagPosition: "bodyClose"
      }]
    });
  }
  ssrContext._ogImagePayloads = payloads;
}
export function resolveComponentName(component) {
  component = component || componentNames?.[0]?.pascalName;
  if (component && componentNames) {
    const originalName = component;
    const normalizedName = originalName.split(".").map((s, i) => i === 0 ? s : s.charAt(0).toUpperCase() + s.slice(1)).join("");
    const inputBase = normalizedName.replace(RE_RENDERER_SUFFIX, "");
    for (const component2 of componentNames) {
      if (component2.pascalName === normalizedName)
        return component2.pascalName;
      const basePascalName = component2.pascalName.replace(RE_RENDERER_SUFFIX, "");
      if (basePascalName === originalName || basePascalName === inputBase)
        return component2.pascalName;
      const prefixes = [
        { prefix: "OgImageCommunity", overlapWord: "Community" },
        { prefix: "OgImageTemplate", overlapWord: "Template" },
        { prefix: "OgImage", overlapWord: "Image" }
      ];
      for (const { prefix, overlapWord } of prefixes) {
        if (!basePascalName.startsWith(prefix))
          continue;
        const withoutPrefix = basePascalName.slice(prefix.length);
        if (withoutPrefix === originalName || withoutPrefix === inputBase)
          return component2.pascalName;
        if (withoutPrefix && withoutPrefix !== overlapWord) {
          const withOverlap = overlapWord + withoutPrefix;
          if (withOverlap === originalName || withOverlap === inputBase)
            return component2.pascalName;
        }
        break;
      }
    }
  }
  return component;
}
export function getOgImagePath(_pagePath, _options) {
  const runtimeConfig = useRuntimeConfig();
  const baseURL = runtimeConfig.app.baseURL;
  const { defaults } = useOgImageRuntimeConfig();
  const extension = _options?.extension || defaults?.extension || "png";
  const isStatic = import.meta.prerender;
  const options = { ..._options, _path: _pagePath };
  const componentName = _options?.component || componentNames?.[0]?.pascalName;
  const component = componentNames?.find((c) => c.pascalName === componentName || c.kebabName === componentName);
  if (component?.hash)
    options._componentHash = component.hash;
  const result = buildOgImageUrl(options, extension, isStatic, defaults);
  const path = joinURL("/", baseURL, result.url);
  return {
    path,
    hash: result.hash
  };
}
export function useOgImageRuntimeConfig() {
  const c = useRuntimeConfig();
  return {
    defaults: {},
    ...c["nuxt-og-image"],
    app: {
      baseURL: c.app.baseURL
    }
  };
}
