import { a as lc, n as isRuleGroupType, r as isRuleGroupTypeIC, t as isRuleGroup } from "./isRuleGroup-DztIOOKa.mjs";
import { produce } from "immer";

//#region src/utils/convertQuery.ts
const combinatorLevels = [
	"or",
	"xor",
	"and"
];
const isSameString = (a, b) => lc(a) === b;
const generateRuleGroupICWithConsistentCombinators = (rg, baseCombinatorLevel = 0) => {
	const baseCombinator = combinatorLevels[baseCombinatorLevel];
	if (!rg.rules.includes(baseCombinator)) return baseCombinatorLevel < combinatorLevels.length - 2 ? generateRuleGroupICWithConsistentCombinators(rg, baseCombinatorLevel + 1) : rg;
	return produce(rg, (draft) => {
		let cursor = 0;
		while (cursor < draft.rules.length - 2) {
			if (isSameString(draft.rules[cursor + 1], baseCombinator)) {
				cursor += 2;
				continue;
			}
			const nextBaseCombinatorIndex = draft.rules.findIndex((r, i) => i > cursor && typeof r === "string" && lc(r) === baseCombinator);
			if (nextBaseCombinatorIndex === -1) {
				draft.rules.splice(cursor, draft.rules.length, generateRuleGroupICWithConsistentCombinators({ rules: draft.rules.slice(cursor) }, baseCombinatorLevel + 1));
				break;
			} else draft.rules.splice(cursor, nextBaseCombinatorIndex - cursor, generateRuleGroupICWithConsistentCombinators({ rules: draft.rules.slice(cursor, nextBaseCombinatorIndex) }, baseCombinatorLevel + 1));
		}
	});
};
/**
* Converts a {@link RuleGroupTypeIC} to {@link RuleGroupType}.
*
* This function is idempotent: {@link RuleGroupType} queries will be
* returned as-is.
*
* @group Query Tools
*/
const convertFromIC = (rg) => {
	if (isRuleGroupType(rg)) return rg;
	const processedRG = generateRuleGroupICWithConsistentCombinators(rg);
	const rulesAsMixedList = processedRG.rules.map((r) => typeof r === "string" || !isRuleGroup(r) ? r : convertFromIC(r));
	const combinator = rulesAsMixedList.length < 2 ? "and" : rulesAsMixedList[1];
	const rules = rulesAsMixedList.filter((r) => typeof r !== "string");
	return {
		...processedRG,
		combinator,
		rules
	};
};
/**
* Converts a {@link RuleGroupType} to {@link RuleGroupTypeIC}.
*
* This function is idempotent: {@link RuleGroupTypeIC} queries will be
* returned as-is.
*
* @group Query Tools
*/
const convertToIC = (rg) => {
	if (isRuleGroupTypeIC(rg)) return rg;
	const { combinator, ...queryWithoutCombinator } = rg;
	const rules = [];
	const { length } = rg.rules;
	for (const [idx, r] of rg.rules.entries()) {
		if (isRuleGroup(r)) rules.push(convertToIC(r));
		else rules.push(r);
		if (combinator && idx < length - 1) rules.push(combinator);
	}
	return {
		...queryWithoutCombinator,
		rules
	};
};

//#endregion
export { convertToIC as n, convertFromIC as t };
//# sourceMappingURL=convertQuery-DAj92cbM.mjs.map