import { p as y, be as J, bf as F, bg as z, bh as M, g as a, Z as $, bi as j, bj as Y, az as Z, bk as H, aF as V, aA as D, ay as _, bl as q, bm as K } from "./index-CNUFa5l3.js";
import { y as O, l as C } from "./graphlib-D2YdGpuK-CM8PX5pf.js";
import { z as Q, V as k, a as U } from "./dagre-DJxg_nfI-BzVw7cNP.js";
var W = 4;
function ee(e) {
  return U(e, W);
}
function b(e) {
  var n = {
    options: {
      directed: e.isDirected(),
      multigraph: e.isMultigraph(),
      compound: e.isCompound()
    },
    nodes: re(e),
    edges: ne(e)
  };
  return C(e.graph()) || (n.value = ee(e.graph())), n;
}
function re(e) {
  return k(e.nodes(), function(n) {
    var r = e.node(n), d = e.parent(n), o = { v: n };
    return C(r) || (o.value = r), C(d) || (o.parent = d), o;
  });
}
function ne(e) {
  return k(e.edges(), function(n) {
    var r = e.edge(n), d = {
      v: n.v,
      w: n.w
    };
    return C(n.name) || (d.name = n.name), C(r) || (d.value = r), d;
  });
}
var f = /* @__PURE__ */ new Map(), E = /* @__PURE__ */ new Map(), G = /* @__PURE__ */ new Map(), te = /* @__PURE__ */ y(() => {
  E.clear(), G.clear(), f.clear();
}, "clear"), I = /* @__PURE__ */ y((e, n) => {
  let r = E.get(n) || [];
  return a.trace("In isDescendant", n, " ", e, " = ", r.includes(e)), r.includes(e);
}, "isDescendant"), ae = /* @__PURE__ */ y((e, n) => {
  let r = E.get(n) || [];
  return a.info("Descendants of ", n, " is ", r), a.info("Edge is ", e), e.v === n || e.w === n ? !1 : r ? r.includes(e.v) || I(e.v, n) || I(e.w, n) || r.includes(e.w) : (a.debug("Tilt, ", n, ",not in descendants"), !1);
}, "edgeInCluster"), R = /* @__PURE__ */ y((e, n, r, d) => {
  a.warn("Copying children of ", e, "root", d, "data", n.node(e), d);
  let o = n.children(e) || [];
  e !== d && o.push(e), a.warn("Copying (nodes) clusterId", e, "nodes", o), o.forEach((l) => {
    if (n.children(l).length > 0) R(l, n, r, d);
    else {
      let i = n.node(l);
      a.info("cp ", l, " to ", d, " with parent ", e), r.setNode(l, i), d !== n.parent(l) && (a.warn("Setting parent", l, n.parent(l)), r.setParent(l, n.parent(l))), e !== d && l !== e ? (a.debug("Setting parent", l, e), r.setParent(l, e)) : (a.info("In copy ", e, "root", d, "data", n.node(e), d), a.debug("Not Setting parent for node=", l, "cluster!==rootId", e !== d, "node!==clusterId", l !== e));
      let s = n.edges(l);
      a.debug("Copying Edges", s), s.forEach((c) => {
        a.info("Edge", c);
        let X = n.edge(c.v, c.w, c.name);
        a.info("Edge data", X, d);
        try {
          ae(c, d) ? (a.info("Copying as ", c.v, c.w, X, c.name), r.setEdge(c.v, c.w, X, c.name), a.info("newGraph edges ", r.edges(), r.edge(r.edges()[0]))) : a.info("Skipping copy of edge ", c.v, "-->", c.w, " rootId: ", d, " clusterId:", e);
        } catch (N) {
          a.error(N);
        }
      });
    }
    a.debug("Removing node", l), n.removeNode(l);
  });
}, "copy"), T = /* @__PURE__ */ y((e, n) => {
  let r = n.children(e), d = [...r];
  for (let o of r) G.set(o, e), d = [...d, ...T(o, n)];
  return d;
}, "extractDescendants"), ie = /* @__PURE__ */ y((e, n, r) => {
  let d = e.edges().filter((s) => s.v === n || s.w === n), o = e.edges().filter((s) => s.v === r || s.w === r), l = d.map((s) => ({
    v: s.v === n ? r : s.v,
    w: s.w === n ? n : s.w
  })), i = o.map((s) => ({
    v: s.v,
    w: s.w
  }));
  return l.filter((s) => i.some((c) => s.v === c.v && s.w === c.w));
}, "findCommonEdges"), S = /* @__PURE__ */ y((e, n, r) => {
  let d = n.children(e);
  if (a.trace("Searching children of id ", e, d), d.length < 1) return e;
  let o;
  for (let l of d) {
    let i = S(l, n, r), s = ie(n, r, i);
    if (i) if (s.length > 0) o = i;
    else return i;
  }
  return o;
}, "findNonClusterChild"), L = /* @__PURE__ */ y((e) => !f.has(e) || !f.get(e).externalConnections ? e : f.has(e) ? f.get(e).id : e, "getAnchorId"), de = /* @__PURE__ */ y((e, n) => {
  if (!e || n > 10) {
    a.debug("Opting out, no graph ");
    return;
  } else a.debug("Opting in, graph ");
  e.nodes().forEach(function(r) {
    e.children(r).length > 0 && (a.warn("Cluster identified", r, " Replacement id in edges: ", S(r, e, r)), E.set(r, T(r, e)), f.set(r, {
      id: S(r, e, r),
      clusterData: e.node(r)
    }));
  }), e.nodes().forEach(function(r) {
    let d = e.children(r), o = e.edges();
    d.length > 0 ? (a.debug("Cluster identified", r, E), o.forEach((l) => {
      I(l.v, r) ^ I(l.w, r) && (a.warn("Edge: ", l, " leaves cluster ", r), a.warn("Descendants of XXX ", r, ": ", E.get(r)), f.get(r).externalConnections = !0);
    })) : a.debug("Not a cluster ", r, E);
  });
  for (let r of f.keys()) {
    let d = f.get(r).id, o = e.parent(d);
    o !== r && f.has(o) && !f.get(o).externalConnections && (f.get(r).id = o);
  }
  e.edges().forEach(function(r) {
    let d = e.edge(r);
    a.warn("Edge " + r.v + " -> " + r.w + ": " + JSON.stringify(r)), a.warn("Edge " + r.v + " -> " + r.w + ": " + JSON.stringify(e.edge(r)));
    let o = r.v, l = r.w;
    if (a.warn("Fix XXX", f, "ids:", r.v, r.w, "Translating: ", f.get(r.v), " --- ", f.get(r.w)), f.get(r.v) || f.get(r.w)) {
      if (a.warn("Fixing and trying - removing XXX", r.v, r.w, r.name), o = L(r.v), l = L(r.w), e.removeEdge(r.v, r.w, r.name), o !== r.v) {
        let i = e.parent(o);
        f.get(i).externalConnections = !0, d.fromCluster = r.v;
      }
      if (l !== r.w) {
        let i = e.parent(l);
        f.get(i).externalConnections = !0, d.toCluster = r.w;
      }
      a.warn("Fix Replacing with XXX", o, l, r.name), e.setEdge(o, l, d, r.name);
    }
  }), a.warn("Adjusted Graph", b(e)), P(e, 0), a.trace(f);
}, "adjustClustersAndEdges"), P = /* @__PURE__ */ y((e, n) => {
  var o, l;
  if (a.warn("extractor - ", n, b(e), e.children("D")), n > 10) {
    a.error("Bailing out");
    return;
  }
  let r = e.nodes(), d = !1;
  for (let i of r) {
    let s = e.children(i);
    d || (d = s.length > 0);
  }
  if (!d) {
    a.debug("Done, no node has children", e.nodes());
    return;
  }
  a.debug("Nodes = ", r, n);
  for (let i of r) if (a.debug("Extracting node", i, f, f.has(i) && !f.get(i).externalConnections, !e.parent(i), e.node(i), e.children("D"), " Depth ", n), !f.has(i)) a.debug("Not a cluster", i, n);
  else if (!f.get(i).externalConnections && e.children(i) && e.children(i).length > 0) {
    a.warn("Cluster without external connections, without a parent and with children", i, n);
    let s = e.graph().rankdir === "TB" ? "LR" : "TB";
    (l = (o = f.get(i)) == null ? void 0 : o.clusterData) != null && l.dir && (s = f.get(i).clusterData.dir, a.warn("Fixing dir", f.get(i).clusterData.dir, s));
    let c = new O({
      multigraph: !0,
      compound: !0
    }).setGraph({
      rankdir: s,
      nodesep: 50,
      ranksep: 50,
      marginx: 8,
      marginy: 8
    }).setDefaultEdgeLabel(function() {
      return {};
    });
    a.warn("Old graph before copy", b(e)), R(i, e, c, i), e.setNode(i, {
      clusterNode: !0,
      id: i,
      clusterData: f.get(i).clusterData,
      label: f.get(i).label,
      graph: c
    }), a.warn("New graph after copy node: (", i, ")", b(c)), a.debug("Old graph after copy", b(e));
  } else a.warn("Cluster ** ", i, " **not meeting the criteria !externalConnections:", !f.get(i).externalConnections, " no parent: ", !e.parent(i), " children ", e.children(i) && e.children(i).length > 0, e.children("D"), n), a.debug(f);
  r = e.nodes(), a.warn("New list of nodes", r);
  for (let i of r) {
    let s = e.node(i);
    a.warn(" Now next level", i, s), s != null && s.clusterNode && P(s.graph, n + 1);
  }
}, "extractor"), A = /* @__PURE__ */ y((e, n) => {
  if (n.length === 0) return [];
  let r = Object.assign([], n);
  return n.forEach((d) => {
    let o = A(e, e.children(d));
    r = [...r, ...o];
  }), r;
}, "sorter"), oe = /* @__PURE__ */ y((e) => A(e, e.children()), "sortNodesByHierarchy"), B = /* @__PURE__ */ y(async (e, n, r, d, o, l) => {
  a.warn("Graph in recursive render:XAX", b(n), o);
  let i = n.graph().rankdir;
  a.trace("Dir in recursive render - dir:", i);
  let s = e.insert("g").attr("class", "root");
  n.nodes() ? a.info("Recursive render XXX", n.nodes()) : a.info("No nodes found for", n), n.edges().length > 0 && a.info("Recursive edges", n.edge(n.edges()[0]));
  let c = s.insert("g").attr("class", "clusters"), X = s.insert("g").attr("class", "edgePaths"), N = s.insert("g").attr("class", "edgeLabels"), h = s.insert("g").attr("class", "nodes");
  await Promise.all(n.nodes().map(async function(g) {
    let t = n.node(g);
    if (o !== void 0) {
      let u = JSON.parse(JSON.stringify(o.clusterData));
      a.trace(`Setting data for parent cluster XXX
 Node.id = `, g, `
 data=`, u.height, `
Parent cluster`, o.height), n.setNode(o.id, u), n.parent(g) || (a.trace("Setting parent", g, o.id), n.setParent(g, o.id, u));
    }
    if (a.info("(Insert) Node XXX" + g + ": " + JSON.stringify(n.node(g))), t == null ? void 0 : t.clusterNode) {
      a.info("Cluster identified XBX", g, t.width, n.node(g));
      let { ranksep: u, nodesep: w } = n.graph();
      t.graph.setGraph({
        ...t.graph.graph(),
        ranksep: u + 25,
        nodesep: w
      });
      let v = await B(h, t.graph, r, d, n.node(g), l), x = v.elem;
      j(t, x), t.diff = v.diff || 0, a.info("New compound node after recursive render XAX", g, "width", t.width, "height", t.height), Y(x, t);
    } else n.children(g).length > 0 ? (a.trace("Cluster - the non recursive path XBX", g, t.id, t, t.width, "Graph:", n), a.trace(S(t.id, n)), f.set(t.id, {
      id: S(t.id, n),
      node: t
    })) : (a.trace("Node - the non recursive path XAX", g, h, n.node(g), i), await Z(h, n.node(g), {
      config: l,
      dir: i
    }));
  })), await (/* @__PURE__ */ y(async () => {
    let g = n.edges().map(async function(t) {
      let u = n.edge(t.v, t.w, t.name);
      a.info("Edge " + t.v + " -> " + t.w + ": " + JSON.stringify(t)), a.info("Edge " + t.v + " -> " + t.w + ": ", t, " ", JSON.stringify(n.edge(t))), a.info("Fix", f, "ids:", t.v, t.w, "Translating: ", f.get(t.v), f.get(t.w)), await H(N, u);
    });
    await Promise.all(g);
  }, "processEdges"))(), a.info("Graph before layout:", JSON.stringify(b(n))), a.info("############################################# XXX"), a.info("###                Layout                 ### XXX"), a.info("############################################# XXX"), Q(n), a.info("Graph after layout:", JSON.stringify(b(n)));
  let p = 0, { subGraphTitleTotalMargin: m } = V(l);
  return await Promise.all(oe(n).map(async function(g) {
    var u;
    let t = n.node(g);
    if (a.info("Position XBX => " + g + ": (" + t.x, "," + t.y, ") width: ", t.width, " height: ", t.height), t == null ? void 0 : t.clusterNode) t.y += m, a.info("A tainted cluster node XBX1", g, t.id, t.width, t.height, t.x, t.y, n.parent(g)), f.get(t.id).node = t, D(t);
    else if (n.children(g).length > 0) {
      a.info("A pure cluster node XBX1", g, t.id, t.x, t.y, t.width, t.height, n.parent(g)), t.height += m, n.node(t.parentId);
      let w = (t == null ? void 0 : t.padding) / 2 || 0, v = ((u = t == null ? void 0 : t.labelBBox) == null ? void 0 : u.height) || 0, x = v - w || 0;
      a.debug("OffsetY", x, "labelHeight", v, "halfPadding", w), await _(c, t), f.get(t.id).node = t;
    } else {
      let w = n.node(t.parentId);
      t.y += m / 2, a.info("A regular node XBX1 - using the padding", t.id, "parent", t.parentId, t.width, t.height, t.x, t.y, "offsetY", t.offsetY, "parent", w, w == null ? void 0 : w.offsetY, t), D(t);
    }
  })), n.edges().forEach(function(g) {
    let t = n.edge(g);
    a.info("Edge " + g.v + " -> " + g.w + ": " + JSON.stringify(t), t), t.points.forEach((u) => u.y += m / 2), q(t, K(X, t, f, r, n.node(g.v), n.node(g.w), d));
  }), n.nodes().forEach(function(g) {
    let t = n.node(g);
    a.info(g, t.type, t.diff), t.isGroup && (p = t.diff);
  }), a.warn("Returning from recursive render XAX", s, p), {
    elem: s,
    diff: p
  };
}, "recursiveRender"), fe = /* @__PURE__ */ y(async (e, n) => {
  var l, i, s, c, X, N;
  let r = new O({
    multigraph: !0,
    compound: !0
  }).setGraph({
    rankdir: e.direction,
    nodesep: ((l = e.config) == null ? void 0 : l.nodeSpacing) || ((s = (i = e.config) == null ? void 0 : i.flowchart) == null ? void 0 : s.nodeSpacing) || e.nodeSpacing,
    ranksep: ((c = e.config) == null ? void 0 : c.rankSpacing) || ((N = (X = e.config) == null ? void 0 : X.flowchart) == null ? void 0 : N.rankSpacing) || e.rankSpacing,
    marginx: 8,
    marginy: 8
  }).setDefaultEdgeLabel(function() {
    return {};
  }), d = n.select("g");
  J(d, e.markers, e.type, e.diagramId), F(), z(), M(), te(), e.nodes.forEach((h) => {
    r.setNode(h.id, { ...h }), h.parentId && r.setParent(h.id, h.parentId);
  }), a.debug("Edges:", e.edges), e.edges.forEach((h) => {
    if (h.start === h.end) {
      let p = h.start, m = p + "---" + p + "---1", g = p + "---" + p + "---2", t = r.node(p);
      r.setNode(m, {
        domId: m,
        id: m,
        parentId: t.parentId,
        labelStyle: "",
        label: "",
        padding: 0,
        shape: "labelRect",
        style: "",
        width: 10,
        height: 10
      }), r.setParent(m, t.parentId), r.setNode(g, {
        domId: g,
        id: g,
        parentId: t.parentId,
        labelStyle: "",
        padding: 0,
        shape: "labelRect",
        label: "",
        style: "",
        width: 10,
        height: 10
      }), r.setParent(g, t.parentId);
      let u = structuredClone(h), w = structuredClone(h), v = structuredClone(h);
      u.label = "", u.arrowTypeEnd = "none", u.endLabelLeft = "", u.endLabelRight = "", u.startLabelLeft = "", u.id = p + "-cyclic-special-1", w.startLabelRight = "", w.startLabelLeft = "", w.endLabelLeft = "", w.endLabelRight = "", w.arrowTypeStart = "none", w.arrowTypeEnd = "none", w.id = p + "-cyclic-special-mid", v.label = "", v.startLabelRight = "", v.startLabelLeft = "", v.arrowTypeStart = "none", t.isGroup && (u.fromCluster = p, v.toCluster = p), v.id = p + "-cyclic-special-2", v.arrowTypeStart = "none", r.setEdge(p, m, u, p + "-cyclic-special-0"), r.setEdge(m, g, w, p + "-cyclic-special-1"), r.setEdge(g, p, v, p + "-cyc<lic-special-2");
    } else r.setEdge(h.start, h.end, { ...h }, h.id);
  }), a.warn("Graph at first:", JSON.stringify(b(r))), de(r), a.warn("Graph after XAX:", JSON.stringify(b(r)));
  let o = $();
  await B(d, r, e.type, e.diagramId, void 0, o);
}, "render");
export {
  fe as render
};
