package de.gecheckt.pdf.umbenenner.application.service;

import java.util.Objects;

/**
 * Utility for limiting extracted document text to the configured maximum character count.
 * <p>
 * The limitation is applied strictly <em>before</em> an AI request is composed.
 * It operates on the extracted text as a character-count boundary without considering
 * word or sentence boundaries, which is intentional: the AI is expected to handle
 * partial text gracefully.
 *
 * <h2>Semantics</h2>
 * <ul>
 *   <li>If the text length does not exceed the configured maximum, it is returned unchanged.</li>
 *   <li>If the text length exceeds the maximum, it is truncated to exactly
 *       {@code maxCharacters} characters.</li>
 * </ul>
 *
 * <h2>Architecture boundary</h2>
 * <p>
 * This limiter does <em>not</em> modify the originally extracted document text stored
 * elsewhere in the pipeline. It produces a new, potentially shorter copy suitable
 * for inclusion in the AI request. The caller is responsible for recording the
 * effective character count (i.e., the length of the returned string) for persistence.
 */
public final class DocumentTextLimiter {

    private DocumentTextLimiter() {
        // Static utility – no instances
    }

    /**
     * Returns the document text limited to {@code maxCharacters} characters.
     * <p>
     * If {@code text.length() <= maxCharacters} the original text is returned unchanged.
     * Otherwise the first {@code maxCharacters} characters are returned as a new string.
     *
     * @param text          the extracted document text; must not be null
     * @param maxCharacters the maximum number of characters to include; must be &gt;= 1
     * @return the text limited to {@code maxCharacters} characters; never null
     * @throws NullPointerException     if {@code text} is null
     * @throws IllegalArgumentException if {@code maxCharacters} is less than 1
     */
    public static String limit(String text, int maxCharacters) {
        Objects.requireNonNull(text, "text must not be null");
        if (maxCharacters < 1) {
            throw new IllegalArgumentException("maxCharacters must be >= 1, but was: " + maxCharacters);
        }
        if (text.length() <= maxCharacters) {
            return text;
        }
        return text.substring(0, maxCharacters);
    }
}
