import { getTag as f } from "./get-tag.js";
const u = (n, o, m, c, s = !1) => {
  const i = m(n), d = n["x-displayName"] || n.name || "Untitled Tag";
  return o.set(i, d), {
    id: i,
    title: d,
    tag: n,
    children: c,
    isGroup: s
  };
}, p = (n, o, m, { getTagId: c, tagsSorter: s, operationsSorter: i }) => {
  const d = n.includes("default"), l = d ? n.filter((a) => a !== "default") : n;
  return s === "alpha" ? l.sort((a, r) => {
    const h = f(o, a).tag["x-displayName"] || a || "Untitle Tag", t = f(o, r).tag["x-displayName"] || r || "Untitled Tag";
    return h.localeCompare(t);
  }) : typeof s == "function" && l.sort((a, r) => s(f(o, a).tag, f(o, r).tag)), d && l.push("default"), l.flatMap((a) => {
    const { tag: r, entries: h } = f(o, a);
    return r["x-internal"] || r["x-scalar-ignore"] ? [] : (i === "alpha" ? h.sort((t, e) => "method" in t && "method" in e ? t.title.localeCompare(e.title) : 0) : i === "method" ? h.sort((t, e) => "method" in t && "method" in e ? t.method.localeCompare(e.method) : 0) : typeof i == "function" && h.sort((t, e) => {
      if (!("method" in t) || !("method" in e))
        return 0;
      const x = "path" in t ? t.path : t.name, y = "path" in e ? e.path : e.name, g = "operation" in t ? t.operation : t.webhook, T = "operation" in e ? e.operation : e.webhook;
      return i(
        { method: t.method, httpVerb: t.method, path: x, operation: g },
        { method: e.method, httpVerb: e.method, path: y, operation: T }
      );
    }), h.length ? u(r, m, c, h) : []);
  });
}, k = (n, o, m, { getTagId: c, tagsSorter: s, operationsSorter: i }) => {
  if (n["x-tagGroups"])
    return n["x-tagGroups"].flatMap((r) => {
      const h = p(r.tags ?? [], o, m, {
        getTagId: c,
        tagsSorter: s,
        operationsSorter: i
      });
      return h.length ? u(r, m, c, h, !0) : [];
    });
  const d = Array.from(o.keys()), l = p(d, o, m, { getTagId: c, tagsSorter: s, operationsSorter: i });
  return l.length === 1 && l[0].title === "default" ? l[0].children ?? [] : l;
};
export {
  k as traverseTags
};
