package com.smyhub.infogenie.infogeniebackendjava.util;

import org.springframework.stereotype.Component;

/**
 * Helpers for processing AI model responses.
 * Mirrors the Go extractOrRaw helper: attempts to parse a JSON string, falls back
 * to returning the raw text unchanged.
 */
@Component
public class AiResponseUtil {

    private static final int MAX_INPUT_LEN = 5000;
    private static final int MAX_CHAT_MSG_COUNT = 20;

    public int getMaxInputLen() {
        return MAX_INPUT_LEN;
    }

    public int getMaxChatMsgCount() {
        return MAX_CHAT_MSG_COUNT;
    }

    /**
     * Truncates input to the configured maximum character limit.
     */
    public String truncateInput(String input) {
        if (input == null) return "";
        return input.length() > MAX_INPUT_LEN ? input.substring(0, MAX_INPUT_LEN) : input;
    }

    /**
     * Masks an API key, showing only the last 4 characters.
     * Returns an empty string for blank keys.
     */
    public String maskApiKey(String key) {
        if (key == null || key.isBlank()) return "";
        if (key.length() <= 4) return "****";
        return "****" + key.substring(key.length() - 4);
    }

    /**
     * Returns true when the provided key value should be treated as a placeholder
     * rather than a real update (blank or contains asterisks).
     */
    public boolean isKeyPlaceholder(String key) {
        return key == null || key.isBlank() || key.contains("****");
    }
}
