package tech.easyflow.agent.config;

import tech.easyflow.common.web.exceptions.BusinessException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Agent 对话体验配置的规范化与校验工具。
 */
public final class AgentInteractionConfigSupport {

    /** 欢迎语最大字符数。 */
    public static final int MAX_WELCOME_MESSAGE_LENGTH = 300;
    /** 猜你想问最大数量。 */
    public static final int MAX_SUGGESTED_QUESTION_COUNT = 6;
    /** 单条猜你想问最大字符数。 */
    public static final int MAX_SUGGESTED_QUESTION_LENGTH = 80;
    /** 输入提示最大字符数。 */
    public static final int MAX_INPUT_PLACEHOLDER_LENGTH = 40;

    private AgentInteractionConfigSupport() {
    }

    /**
     * 规范化并校验对话体验配置。
     *
     * @param source 原始配置
     * @return 仅包含受支持字段的稳定配置
     * @throws BusinessException 配置字段类型或内容不合法时抛出
     */
    public static Map<String, Object> normalize(Map<String, Object> source) {
        Map<String, Object> config = source == null ? Map.of() : source;
        String welcomeMessage = optionalString(config.get("welcomeMessage"), "欢迎语");
        if (welcomeMessage.length() > MAX_WELCOME_MESSAGE_LENGTH) {
            throw new BusinessException("欢迎语不能超过 300 个字符");
        }

        String inputPlaceholder = optionalString(config.get("inputPlaceholder"), "输入提示");
        if (inputPlaceholder.contains("\n") || inputPlaceholder.contains("\r")) {
            throw new BusinessException("输入提示仅支持单行文本");
        }
        if (inputPlaceholder.length() > MAX_INPUT_PLACEHOLDER_LENGTH) {
            throw new BusinessException("输入提示不能超过 40 个字符");
        }

        List<String> suggestedQuestions = normalizeSuggestedQuestions(config.get("suggestedQuestions"));
        Map<String, Object> normalized = new LinkedHashMap<>();
        normalized.put("welcomeMessage", welcomeMessage);
        normalized.put("suggestedQuestions", suggestedQuestions);
        normalized.put("inputPlaceholder", inputPlaceholder);
        return normalized;
    }

    /**
     * 规范化猜你想问列表，过滤空项并保留原有顺序。
     *
     * @param value 原始列表值
     * @return 规范化后的问题列表
     * @throws BusinessException 列表类型、数量、长度或重复性不合法时抛出
     */
    private static List<String> normalizeSuggestedQuestions(Object value) {
        if (value == null) {
            return List.of();
        }
        if (!(value instanceof Collection<?> values)) {
            throw new BusinessException("猜你想问格式不正确");
        }
        List<String> normalized = new ArrayList<>();
        Set<String> uniqueQuestions = new LinkedHashSet<>();
        for (Object item : values) {
            if (!(item instanceof String question)) {
                throw new BusinessException("猜你想问仅支持文本内容");
            }
            String trimmedQuestion = question.trim();
            if (trimmedQuestion.isEmpty()) {
                continue;
            }
            if (trimmedQuestion.length() > MAX_SUGGESTED_QUESTION_LENGTH) {
                throw new BusinessException("单条猜你想问不能超过 80 个字符");
            }
            if (!uniqueQuestions.add(trimmedQuestion)) {
                throw new BusinessException("猜你想问不能重复");
            }
            normalized.add(trimmedQuestion);
        }
        if (normalized.size() > MAX_SUGGESTED_QUESTION_COUNT) {
            throw new BusinessException("猜你想问最多配置 6 条");
        }
        return normalized;
    }

    /**
     * 将可选字段转换为去除首尾空白的文本。
     *
     * @param value 原始字段值
     * @param fieldName 字段名称
     * @return 规范化后的文本
     * @throws BusinessException 字段不是文本时抛出
     */
    private static String optionalString(Object value, String fieldName) {
        if (value == null) {
            return "";
        }
        if (!(value instanceof String text)) {
            throw new BusinessException(fieldName + "格式不正确");
        }
        return text.trim();
    }
}
