function isIndexInsideCodeBlock(content, indexToTest) {
  let fenceCount = 0;
  let searchPos = 0;
  while (searchPos < content.length) {
    const nextFence = content.indexOf("```", searchPos);
    if (nextFence === -1 || nextFence >= indexToTest) {
      break;
    }
    fenceCount++;
    searchPos = nextFence + 3;
  }
  return fenceCount % 2 === 1;
}
function findEnclosingCodeBlockStart(content, index) {
  if (!isIndexInsideCodeBlock(content, index)) {
    return -1;
  }
  let currentSearchPos = 0;
  while (currentSearchPos < index) {
    const blockStartIndex = content.indexOf("```", currentSearchPos);
    if (blockStartIndex === -1 || blockStartIndex >= index) {
      break;
    }
    const blockEndIndex = content.indexOf("```", blockStartIndex + 3);
    if (blockStartIndex < index) {
      if (blockEndIndex === -1 || index < blockEndIndex + 3) {
        return blockStartIndex;
      }
    }
    if (blockEndIndex === -1) break;
    currentSearchPos = blockEndIndex + 3;
  }
  return -1;
}
function findLastSafeSplitPoint(content) {
  const enclosingBlockStart = findEnclosingCodeBlockStart(content, content.length);
  if (enclosingBlockStart !== -1) {
    return enclosingBlockStart;
  }
  let searchStartIndex = content.length;
  while (searchStartIndex >= 0) {
    const dnlIndex = content.lastIndexOf("\n\n", searchStartIndex);
    if (dnlIndex === -1) {
      break;
    }
    const potentialSplitPoint = dnlIndex + 2;
    if (!isIndexInsideCodeBlock(content, potentialSplitPoint)) {
      return potentialSplitPoint;
    }
    searchStartIndex = dnlIndex - 1;
  }
  return content.length;
}
function findLastSafeNewline(content) {
  let searchPos = content.length;
  while (searchPos > 0) {
    const nlIndex = content.lastIndexOf("\n", searchPos - 1);
    if (nlIndex === -1) {
      break;
    }
    if (!isIndexInsideCodeBlock(content, nlIndex)) {
      return nlIndex + 1;
    }
    searchPos = nlIndex;
  }
  return -1;
}
const MIN_PARAGRAPH_SPLIT_LENGTH = 200;
const MAX_PENDING_LENGTH = 300;
function checkForSplit(content) {
  if (content.length < MIN_PARAGRAPH_SPLIT_LENGTH) {
    return { shouldSplit: false };
  }
  const paragraphSplitPoint = findLastSafeSplitPoint(content);
  if (paragraphSplitPoint > 80 && paragraphSplitPoint < content.length - 20) {
    return {
      shouldSplit: true,
      splitIndex: paragraphSplitPoint,
      before: content.substring(0, paragraphSplitPoint),
      after: content.substring(paragraphSplitPoint)
    };
  }
  if (content.length > MAX_PENDING_LENGTH) {
    const lineSplitPoint = findLastSafeNewline(content);
    if (lineSplitPoint > 80 && lineSplitPoint < content.length - 20) {
      return {
        shouldSplit: true,
        splitIndex: lineSplitPoint,
        before: content.substring(0, lineSplitPoint),
        after: content.substring(lineSplitPoint)
      };
    }
  }
  return { shouldSplit: false };
}
export {
  checkForSplit,
  findLastSafeNewline,
  findLastSafeSplitPoint
};
