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