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