import { createWorkspaceStore as v, createActiveEntitiesStore as y } from "@scalar/api-client/store";
import { measureAsync as P } from "@scalar/helpers/testing/measure";
import { normalize as w, upgrade as O, dereference as V } from "@scalar/openapi-parser";
import { apiReferenceConfigurationSchema as D } from "@scalar/types/api-reference";
import { computed as f, toValue as t, ref as l, watch as F } from "vue";
import { useDocumentFetcher as I } from "./useDocumentFetcher.js";
function C({
  originalDocument: c,
  dereferencedDocument: o,
  configuration: i
}) {
  const { originalDocument: d } = I({
    configuration: i
  }), s = f(() => c ? t(c) : t(d)), n = l(""), h = f(() => o ? t(o) : t(u)), u = l({
    openapi: "3.1.0",
    info: {
      title: "",
      version: ""
    },
    paths: {}
  });
  F(
    () => t(s),
    async (a) => {
      if (!a)
        return;
      const e = w(a);
      if (e === void 0) {
        console.error("Failed to parse the OpenAPI document:", a);
        return;
      }
      if (n.value = typeof e == "object" && (e.openapi || e.swagger) || "", o)
        return;
      const S = !n.value.startsWith("3.1") ? (
        // Upgrade needed
        O(e).specification
      ) : (
        // Skip the upgrade
        e
      ), A = await P("dereference", async () => {
        const { schema: p, errors: r } = await V(S);
        return r != null && r.length && console.warn(
          `Please open an issue on https://github.com/scalar/scalar
`,
          `Scalar OpenAPI Parser Warning:
`,
          r
        ), p === void 0 && console.error("Failed to dereference the OpenAPI document", r), p;
      });
      u.value = A;
    },
    { immediate: !0 }
  );
  const m = v({
    useLocalStorage: !1,
    ...t(i) ?? D.parse({})
  }), g = y(m);
  return {
    originalDocument: s,
    originalOpenApiVersion: n,
    dereferencedDocument: h,
    workspaceStore: m,
    activeEntitiesStore: g
  };
}
export {
  C as useDocumentSource
};
