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