/**
 * Text trimming utilities for AI-generated content.
 * Ensures AI output respects field character limits while preserving meaning.
 */

/**
 * Trims text to a maximum character length while preserving sentence boundaries.
 *
 * Strategy:
 * 1. If text fits within maxLength, return as-is.
 * 2. Try cutting at the last sentence boundary (period, exclamation, question mark) within the limit.
 * 3. Fallback to the last word boundary within the limit + "...".
 * 4. Hard cut with "..." as last resort.
 *
 * @param text - The text to trim
 * @param maxLength - Maximum character length
 * @returns Trimmed string, or null if the result would be too short to be meaningful (< 20 chars)
 */
export function trimToLength(text: string, maxLength: number): string | null {
  if (!text || typeof text !== 'string') return text || null;
  if (text.length <= maxLength) return text;

  // Never trim to less than 20 characters — not meaningful
  if (maxLength < 20) return null;

  // Try sentence boundary (period, exclamation, question mark followed by space or end)
  const sentenceEndRegex = /[.!?](\s|$)/g;
  let lastSentenceEnd = -1;
  let match;
  while ((match = sentenceEndRegex.exec(text)) !== null) {
    if (match.index + 1 <= maxLength - 1) {
      lastSentenceEnd = match.index + 1;
    }
  }
  if (lastSentenceEnd >= 20) {
    return text.substring(0, lastSentenceEnd).trimEnd();
  }

  // Try word boundary
  const truncated = text.substring(0, maxLength);
  const lastSpace = truncated.lastIndexOf(' ');
  if (lastSpace >= 20) {
    return truncated.substring(0, lastSpace).trimEnd() + '...';
  }

  // Hard cut with ellipsis
  return text.substring(0, maxLength - 3).trimEnd() + '...';
}

/**
 * Trims an array of strings so that their combined length (joined by newlines)
 * does not exceed maxLength. Removes items from the end to fit.
 *
 * @param items - Array of strings to trim
 * @param maxLength - Maximum combined character length
 * @returns Trimmed array, or null if no items can fit
 */
export function trimArrayToCombinedLength(items: string[], maxLength: number): string[] | null {
  if (!items || items.length === 0) return items;
  const combined = items.join('\n');
  if (combined.length <= maxLength) return items;

  // Remove items from the end until we fit
  const result: string[] = [];
  let currentLength = 0;
  for (const item of items) {
    const addLength = item.length + (result.length > 0 ? 1 : 0); // +1 for newline
    if (currentLength + addLength > maxLength) break;
    result.push(item);
    currentLength += addLength;
  }

  return result.length >= 1 ? result : null;
}