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