import { redirectToProxy as b, normalizeRequestMethod as P, validRequestMethods as j } from "@scalar/api-client";
import { load as M, dereference as q } from "@scalar/openapi-parser";
import { fetchUrls as C } from "@scalar/openapi-parser/plugins/fetch-urls";
import { createEmptySpecification as m } from "./createEmptySpecification.js";
const U = (p, {
  proxy: t
} = {}) => new Promise(async (o, h) => {
  var s;
  try {
    if (!p)
      return o(
        u(m())
      );
    const i = performance.now(), { filesystem: r } = await M(p, {
      plugins: [
        C({
          fetch: (a) => (console.log("FETCH"), console.log("url", a), console.log("proxy", t), fetch(t ? b(t, a) : a))
        })
      ]
    }), { schema: e, errors: n } = await q(r), c = performance.now();
    return console.log(`dereference: ${Math.round(c - i)} ms`), n != null && n.length && console.warn(
      `Please open an issue on https://github.com/scalar/scalar
`,
      `Scalar OpenAPI Parser Warning:
`,
      n
    ), e === void 0 ? (h(((s = n == null ? void 0 : n[0]) == null ? void 0 : s.message) ?? "Failed to parse the OpenAPI file."), o(
      u(m())
    )) : o(u(e));
  } catch (i) {
    h(i);
  }
  return o(
    u(m())
  );
}), u = (p) => {
  let t = {};
  p && typeof p == "object" ? t = structuredClone(p) : t = m(), t.tags || (t.tags = []), t.paths || (t.paths = {});
  const o = {};
  return Object.keys(t.webhooks ?? {}).forEach((s) => {
    var i;
    Object.keys(((i = t.webhooks) == null ? void 0 : i[s]) ?? {}).forEach((r) => {
      var n, c, a;
      const e = (n = t.webhooks) == null ? void 0 : n[s][r];
      (e == null ? void 0 : e["x-internal"]) !== !0 && (o[s] === void 0 && (o[s] = {}), o[s][r] = {
        // Transformed data
        httpVerb: P(r),
        path: s,
        operationId: (e == null ? void 0 : e.operationId) || s,
        name: (e == null ? void 0 : e.summary) || s || "",
        description: (e == null ? void 0 : e.description) || "",
        pathParameters: (a = (c = t.paths) == null ? void 0 : c[s]) == null ? void 0 : a.parameters,
        // Original webhook
        information: {
          ...e
        }
      });
    });
  }), Object.keys(t.paths).forEach((s) => {
    Object.keys(t.paths[s]).filter(
      (r) => j.includes(r.toUpperCase())
    ).forEach((r) => {
      var c, a, g, w, y, x;
      const e = t.paths[s][r];
      if (e === void 0 || e["x-internal"] === !0)
        return;
      const n = {
        httpVerb: P(r),
        path: s,
        operationId: e.operationId || s,
        name: e.summary || s || "",
        description: e.description || "",
        information: {
          ...e
        },
        pathParameters: (a = (c = t.paths) == null ? void 0 : c[s]) == null ? void 0 : a.parameters
      };
      if (!e.tags || e.tags.length === 0) {
        (g = t.tags) != null && g.find(
          (f) => f.name === "default"
        ) || (w = t.tags) == null || w.push({
          name: "default",
          description: "",
          operations: []
        });
        const d = (y = t.tags) == null ? void 0 : y.findIndex(
          (f) => f.name === "default"
        );
        d >= 0 && ((x = t.tags[d]) == null || x.operations.push(n));
      } else
        e.tags.forEach((d) => {
          var I, O, E;
          const f = (I = t.tags) == null ? void 0 : I.findIndex(
            // @ts-expect-error TODO: The types are just screwed, needs refactoring
            (R) => R.name === d
          );
          f === -1 && ((O = t.tags) == null || O.push({
            name: d,
            description: ""
          }));
          const l = f !== -1 ? f : t.tags.length - 1;
          typeof ((E = t.tags[l]) == null ? void 0 : E.operations) > "u" && (t.tags[l].operations = []), t.tags[l].operations.push(n);
        });
    });
  }), {
    ...t,
    webhooks: o
  };
};
export {
  U as parse
};
