package dev.sonpx.loyalty.mcp.util;

import java.text.Normalizer;
import java.util.Set;

/**
 * Utility for sanitizing search parameters passed to MCP tools.
 */
public class SearchUtils {

    private static final Set<String> GENERIC_KEYWORDS = Set.of(
            "chien dich", "chiendich",
            "danh sach", "danhsach",
            "campaign", "campaigns",
            "rule", "rules",
            "the le", "thele",
            "tat ca", "tatca",
            "tat ca chien dich",
            "danh sach chien dich",
            "danh sach rule",
            "danh sach the le",
            "list", "show", "xem"
    );

    /**
     * Sanitizes the input search string.
     * If the search term consists only of generic query noise (e.g. "chiến dịch", "danh sách chiến dịch", "campaign"),
     * returns null so the API returns all items rather than filtering by the word "chiến dịch".
     *
     * @param search the raw search string from LLM tool call
     * @return cleaned search string or null if generic
     */
    public static String sanitizeSearch(String search) {
        if (search == null || search.isBlank()) {
            return null;
        }

        String trimmed = search.trim();
        String normalized = removeAccents(trimmed.toLowerCase());

        if (GENERIC_KEYWORDS.contains(normalized)) {
            return null;
        }

        // Strip leading/trailing generic intent words
        String cleaned = normalized
                .replaceAll("^(danh sach|chien dich|campaign|rule|the le|tat ca|xem|list)\\s+", "")
                .replaceAll("\\s+(danh sach|chien dich|campaign|rule|the le|tat ca)$", "")
                .trim();

        if (cleaned.isEmpty() || GENERIC_KEYWORDS.contains(cleaned)) {
            return null;
        }

        return trimmed;
    }

    private static String removeAccents(String src) {
        return Normalizer.normalize(src, Normalizer.Form.NFD)
                .replaceAll("\\p{M}", "")
                .replace("đ", "d")
                .replace("Đ", "d");
    }
}
