import { redirectToProxy as A, shouldIgnoreEntity as u } from "@scalar/oas-utils/helpers";
import { load as M, dereference as R } from "@scalar/openapi-parser";
import { fetchUrls as q } from "@scalar/openapi-parser/plugins/fetch-urls";
import { createEmptySpecification as O } from "./createEmptySpecification.js";
import { normalizeRequestMethod as $ } from "../legacy/helpers/normalizeRequestMethod.js";
import { validRequestMethods as D } from "../legacy/fixtures/httpRequestMethods.js";
const G = (m, {
  proxyUrl: e,
  source: h
} = {}) => new Promise(async (l, g) => {
  var y;
  try {
    if (!m)
      return l(x(O()));
    const s = performance.now(), { filesystem: c } = await M(m, {
      source: h,
      plugins: [
        q({
          fetch: async (a) => {
            const n = await fetch(e ? A(e, a) : a);
            return n.ok ? console.info(`fetch($ref): ${a} (${Math.round((await n.clone().text()).length / 1024)} kB)`) : console.error(`fetch($ref): ${a} (${n.status} ${n.statusText})`), n;
          }
        })
      ]
    }), { schema: o, errors: t } = await R(c), r = performance.now();
    return console.info(`dereference: ${Math.round(r - s)} ms`), t != null && t.length && console.warn(
      `Please open an issue on https://github.com/scalar/scalar
`,
      `Scalar OpenAPI Parser Warning:
`,
      t
    ), o === void 0 ? (g(((y = t == null ? void 0 : t[0]) == null ? void 0 : y.message) ?? "Failed to parse the OpenAPI file."), l(x(O()))) : l(x(o));
  } catch (s) {
    console.error("[@scalar/api-reference]", "Failed to parse the OpenAPI document. It might be invalid?"), console.error(s), g(s);
  }
  return l(x(O()));
}), x = (m) => {
  var g, y;
  let e = {};
  m && typeof m == "object" ? e = structuredClone(m) : e = O(), e.tags || (e.tags = []), e.paths || (e.paths = {}), e.components || (e.components = {}), e.webhooks || (e.webhooks = {}), e.servers || (e.servers = []), e.security || (e.security = []), e.externalDocs || (e.externalDocs = {});
  const h = {};
  return Object.keys(e.webhooks ?? {}).forEach((s) => {
    var c;
    Object.keys(((c = e.webhooks) == null ? void 0 : c[s]) ?? {}).forEach((o) => {
      var r, a, n, w;
      const t = (r = e.webhooks) == null ? void 0 : r[s][o];
      if (!(!t || u(t))) {
        if (Array.isArray(t.tags)) {
          const i = (a = t.tags) == null ? void 0 : a.map(
            (f) => {
              var I;
              return (I = e.tags) == null ? void 0 : I.find((p) => p.name === f);
            }
          );
          if (t.tags = i == null ? void 0 : i.filter((f) => !u(f)), i != null && i.some((f) => u(f)))
            return;
        }
        h[s] === void 0 && (h[s] = {}), h[s][o] = {
          // Transformed data
          httpVerb: $(o),
          path: s,
          operationId: (t == null ? void 0 : t.operationId) || s,
          name: (t == null ? void 0 : t.summary) || s || "",
          description: (t == null ? void 0 : t.description) || "",
          pathParameters: (w = (n = e.paths) == null ? void 0 : n[s]) == null ? void 0 : w.parameters,
          // Original webhook
          information: {
            ...t
          }
        };
      }
    });
  }), Object.keys(((g = e.components) == null ? void 0 : g.schemas) ?? {}).forEach((s) => {
    var c, o, t, r;
    u((o = (c = e.components) == null ? void 0 : c.schemas) == null ? void 0 : o[s]) && ((r = (t = e.components) == null ? void 0 : t.schemas) == null || delete r[s]);
  }), Object.keys(e.paths).forEach((s) => {
    Object.keys(e.paths[s]).filter(
      (o) => D.includes(o.toUpperCase())
    ).forEach((o) => {
      var a, n, w, i, f, I;
      const t = e.paths[s][o];
      if (t === void 0 || u(t))
        return;
      const r = {
        httpVerb: $(o),
        path: s,
        operationId: t.operationId || s,
        name: t.summary || s || "",
        description: t.description || "",
        information: {
          ...t
        },
        pathParameters: (n = (a = e.paths) == null ? void 0 : a[s]) == null ? void 0 : n.parameters
      };
      if (!t.tags || t.tags.length === 0) {
        (w = e.tags) != null && w.find((d) => d.name === "default") || (i = e.tags) == null || i.push({
          name: "default",
          description: "",
          operations: []
        });
        const p = (f = e.tags) == null ? void 0 : f.findIndex(
          (d) => d.name === "default"
        );
        p >= 0 && ((I = e.tags[p]) == null || I.operations.push(r));
      } else
        t.tags.forEach((p) => {
          var k, E, P;
          const d = (k = e.tags) == null ? void 0 : k.findIndex((j) => j.name === p);
          d === -1 && ((E = e.tags) == null || E.push({
            name: p,
            description: ""
          }));
          const b = d !== -1 ? d : e.tags.length - 1;
          typeof ((P = e.tags[b]) == null ? void 0 : P.operations) > "u" && (e.tags[b].operations = []), e.tags[b].operations.push(r);
        });
    });
  }), e.tags = (y = e.tags) == null ? void 0 : y.filter((s) => !u(s)), {
    ...e,
    webhooks: h
  };
};
export {
  G as parse
};
