import { findFenceSpanAt, isSafeFenceBreak, parseFenceSpans } from "./fences.js";
//#region src/markdown/chunk.ts
/**
* Text chunking utilities for markdown processing
*
* Provides fence-aware text splitting for Telegram message limits.
*/
/**
* Split text into chunks that fit within a character limit.
* Tries to break at natural boundaries (newlines, word boundaries).
*/
function chunkText(text, limit) {
	if (!text) return [];
	if (limit <= 0) return [text];
	if (text.length <= limit) return [text];
	const chunks = [];
	let remaining = text;
	while (remaining.length > limit) {
		const breakIdx = findBreakPoint(remaining.slice(0, limit), remaining, limit);
		let rawChunk = remaining.slice(0, breakIdx);
		if (!rawChunk) {
			rawChunk = remaining.slice(0, limit);
			chunks.push(rawChunk);
			remaining = remaining.slice(limit);
			continue;
		}
		const brokeOnSeparator = breakIdx < remaining.length && /\s/.test(remaining[breakIdx]);
		const nextStart = Math.min(remaining.length, breakIdx + (brokeOnSeparator ? 1 : 0));
		let next = remaining.slice(nextStart);
		next = stripLeadingNewlines(next);
		chunks.push(rawChunk);
		remaining = next;
	}
	if (remaining.length) chunks.push(remaining);
	return chunks;
}
/**
* Find a good break point in the window, considering fence boundaries.
*/
function findBreakPoint(window, remaining, limit) {
	const spans = parseFenceSpans(remaining);
	let lastNewline = -1;
	let lastWhitespace = -1;
	for (let i = 0; i < window.length; i++) {
		if (!isSafeFenceBreak(spans, i)) continue;
		const char = window[i];
		if (char === "\n") lastNewline = i;
		else if (/\s/.test(char)) lastWhitespace = i;
	}
	if (lastNewline > 0) return lastNewline;
	if (lastWhitespace > 0) return lastWhitespace;
	const fence = findFenceSpanAt(spans, limit);
	if (fence) {
		const fenceEnd = fence.start + fence.openLine.length;
		if (fenceEnd < limit && fenceEnd > 0) return fenceEnd;
	}
	return limit;
}
function stripLeadingNewlines(value) {
	let i = 0;
	while (i < value.length && value[i] === "\n") i++;
	return i > 0 ? value.slice(i) : value;
}
//#endregion
export { chunkText };

//# sourceMappingURL=chunk.js.map