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