def sentence_safe_trim(text: str, max_chars: int) -> str: """ Trim text to the last complete sentence within max_chars. Handles both Devanagari '।' and standard '.' full stops. If no sentence boundary is found, falls back to word boundary to avoid word cut-offs. """ if len(text) <= max_chars: return text truncated = text[:max_chars] # Find the last sentence boundary last_devanagari = truncated.rfind('।') last_period = truncated.rfind('.') last_boundary = max(last_devanagari, last_period) if last_boundary > 0: return truncated[:last_boundary + 1].strip() # Fallback 1: word boundary (space, newline) if no full stop last_space = max(truncated.rfind(' '), truncated.rfind('\n')) if last_space > 0: return truncated[:last_space].strip() + '...' # Fallback 2: hard trim return truncated