import { defu } from "defu";
import { useScript } from "./composables/useScript.js";
import { parse } from "#nuxt-scripts-validator";
import { useRuntimeConfig } from "#imports";
function validateScriptInputSchema(key, schema, options) {
  if (import.meta.dev) {
    try {
      parse(schema, options);
    } catch (_e) {
      const e = _e;
      console.error(e.issues.map((i) => `${key}.${i.path?.map((i2) => i2.key).join(",")}: ${i.message}`).join("\n"));
    }
  }
}
export function scriptRuntimeConfig(key) {
  return (useRuntimeConfig().public.scripts || {})[key];
}
export function useRegistryScript(key, optionsFn, _userOptions) {
  const scriptConfig = scriptRuntimeConfig(key);
  const userOptions = Object.assign(_userOptions || {}, typeof scriptConfig === "object" ? scriptConfig : {});
  const options = optionsFn(userOptions);
  const scriptInput = defu(userOptions.scriptInput, options.scriptInput, { key });
  const scriptOptions = Object.assign(userOptions?.scriptOptions || {}, options.scriptOptions || {});
  const init = scriptOptions.beforeInit;
  scriptOptions.beforeInit = () => {
    if (import.meta.dev && !scriptOptions.skipValidation && options.schema) {
      if (!userOptions.scriptInput?.src) {
        validateScriptInputSchema(key, options.schema, userOptions);
      }
    }
    init?.();
    if (import.meta.client) {
      options.clientInit?.();
    }
  };
  return useScript(scriptInput, scriptOptions);
}
