const DEFAULT_HEAD_BYTE_BUDGET_RATIO = 0.5;
const DEFAULT_HEAD_LINE_BUDGET_RATIO = 0.5;
export function createTextOverflowPreview(content, options) {
    const originalBytes = Buffer.byteLength(content, "utf8");
    const originalLines = countTextLines(content);
    if (originalBytes <= options.maxBytes && originalLines <= options.maxLines) {
        return {
            originalBytes,
            originalLines,
            preview: content,
            truncated: false,
        };
    }
    const headByteBudget = Math.max(1, Math.min(options.maxBytes, options.headByteBudget ?? Math.floor(options.maxBytes * DEFAULT_HEAD_BYTE_BUDGET_RATIO)));
    const tailByteBudget = Math.max(1, options.maxBytes - headByteBudget);
    const headLineBudget = Math.max(1, Math.min(options.maxLines, options.headLineBudget ?? Math.floor(options.maxLines * DEFAULT_HEAD_LINE_BUDGET_RATIO)));
    const tailLineBudget = Math.max(1, options.maxLines - headLineBudget);
    const head = takeHeadByBudget(content, headLineBudget, headByteBudget).trimEnd();
    const tail = takeTailByBudget(content, tailLineBudget, tailByteBudget).trimStart();
    const parts = [head, options.omissionMessage, tail].filter((value) => value.length > 0);
    return {
        originalBytes,
        originalLines,
        preview: parts.join("\n\n"),
        truncated: true,
    };
}
export function countTextLines(content) {
    if (content.length === 0) {
        return 0;
    }
    let lines = 1;
    for (let index = 0; index < content.length; index += 1) {
        if (content[index] === "\n") {
            lines += 1;
        }
    }
    return lines;
}
function takeHeadByBudget(content, maxLines, maxBytes) {
    if (content.length === 0) {
        return "";
    }
    let bytes = 0;
    let lines = 1;
    let end = 0;
    for (; end < content.length; end += 1) {
        const character = content[end];
        const nextBytes = Buffer.byteLength(character, "utf8");
        const nextLines = character === "\n" ? lines + 1 : lines;
        if (bytes + nextBytes > maxBytes || nextLines > maxLines + 1) {
            break;
        }
        bytes += nextBytes;
        lines = nextLines;
    }
    return content.slice(0, end);
}
function takeTailByBudget(content, maxLines, maxBytes) {
    if (content.length === 0) {
        return "";
    }
    let bytes = 0;
    let lines = 1;
    let start = content.length;
    for (let index = content.length - 1; index >= 0; index -= 1) {
        const character = content[index];
        const nextBytes = Buffer.byteLength(character, "utf8");
        const nextLines = character === "\n" ? lines + 1 : lines;
        if (bytes + nextBytes > maxBytes || nextLines > maxLines + 1) {
            break;
        }
        bytes += nextBytes;
        lines = nextLines;
        start = index;
    }
    return content.slice(start);
}
//# sourceMappingURL=output-overflow.js.map