import { isMap, isPair, isScalar, isSeq, parseDocument } from "yaml";
//#region src/v2/features/editor/helpers/yaml/get-yaml-node-range-from-path.ts
var isValidYamlRange = (range) => Array.isArray(range) && typeof range[0] === "number" && typeof range[1] === "number";
var safeParseDocument = (yamlText) => {
	try {
		return parseDocument(yamlText);
	} catch {
		return null;
	}
};
/**
* Finds the byte range (offset) in the YAML text corresponding to a JSON path.
* Given a YAML string and a path (array of segments), parses the document and walks
* down the tree to find the target node or key, returning its start and end offsets.
* Will prefer to highlight the "key" part for map entries, to avoid highlighting the value which
* might be offset due to block structure.
*
* @param yamlText The YAML string
* @param path An array representing the path to traverse
* @returns The byte offsets in the YAML string of the node (or null if not found)
*/
var getYamlNodeRangeFromPath = (yamlText, path) => {
	const doc = safeParseDocument(yamlText);
	if (!doc) return null;
	let current = doc.contents;
	let lastPair = null;
	for (const segment of path) {
		if (isMap(current)) {
			const key = String(segment);
			const pair = current.items.find((p) => {
				if (!isPair(p)) return false;
				const pairKey = p.key;
				return isScalar(pairKey) ? String(pairKey.value) === key : String(pairKey) === key;
			});
			if (!pair || !isPair(pair)) return null;
			lastPair = pair;
			current = pair.value;
			continue;
		}
		if (isSeq(current)) {
			const index = typeof segment === "number" ? segment : Number.parseInt(String(segment), 10);
			if (!Number.isFinite(index) || index < 0 || index >= current.items.length) return null;
			lastPair = null;
			current = current.items[index];
			continue;
		}
		return null;
	}
	if (lastPair && isPair(lastPair)) {
		const keyRange = lastPair.key?.range;
		const valueRange = lastPair.value?.range;
		if (!isValidYamlRange(keyRange)) return null;
		const startOffset = Math.max(0, keyRange[0]);
		return {
			startOffset,
			endOffset: isValidYamlRange(valueRange) ? Math.max(startOffset, valueRange[1]) : Math.max(startOffset, keyRange[1])
		};
	}
	const nodeRange = current?.range;
	if (!isValidYamlRange(nodeRange)) return null;
	const startOffset = Math.max(0, nodeRange[0]);
	return {
		startOffset,
		endOffset: Math.max(startOffset, nodeRange[1])
	};
};
//#endregion
export { getYamlNodeRangeFromPath };

//# sourceMappingURL=get-yaml-node-range-from-path.js.map