const MAX_LENGTH = 4096;

export function chunkMessage(text: string): string[] {
  if (text.length <= MAX_LENGTH) return [text];

  const chunks: string[] = [];
  const paragraphs = text.split('\n\n');

  let current = '';

  for (const paragraph of paragraphs) {
    if (paragraph.length > MAX_LENGTH) {
      // Flush current chunk
      if (current) {
        chunks.push(current.trim());
        current = '';
      }
      // Split long paragraph on newlines
      const lines = paragraph.split('\n');
      for (const line of lines) {
        if (line.length > MAX_LENGTH) {
          // Flush current
          if (current) {
            chunks.push(current.trim());
            current = '';
          }
          // Hard-split long line
          for (let i = 0; i < line.length; i += MAX_LENGTH) {
            chunks.push(line.slice(i, i + MAX_LENGTH));
          }
        } else if (current.length + 1 + line.length > MAX_LENGTH) {
          chunks.push(current.trim());
          current = line;
        } else {
          current += (current ? '\n' : '') + line;
        }
      }
    } else if (current.length + 2 + paragraph.length > MAX_LENGTH) {
      chunks.push(current.trim());
      current = paragraph;
    } else {
      current += (current ? '\n\n' : '') + paragraph;
    }
  }

  if (current.trim()) {
    chunks.push(current.trim());
  }

  return chunks;
}
