package com.seer.teach.teacher.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.teacher.module.entity.PromptModulesEntity;
import com.seer.teach.teacher.module.mapper.PromptModulesMapper;
import com.seer.teach.teacher.service.PromptModulesService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 语音指令模块表 服务实现类
 * </p>
 *
 * @author Wang
 * @since 2025-10-28 17:23:03
 */
@Service
public class PromptModulesServiceImpl extends ServiceImpl<PromptModulesMapper, PromptModulesEntity> implements PromptModulesService {

    @Override
    public PromptModulesEntity matchModuleByText(String text) {
        if (!StringUtils.hasText(text)) {
            return null;
        }

        text = text.replaceAll("[\\pP\\pS\\s]+", "");

        List<PromptModulesEntity> modules = this.list(
                new LambdaQueryWrapper<PromptModulesEntity>()
                        .eq(PromptModulesEntity::getStatus, 1)
        );

        // 记录匹配结果（模块 → 匹配次数）
        List<PromptModulesEntity> matched = new ArrayList<>();

        for (PromptModulesEntity module : modules) {
            // 获取关键词与排除词
            List<String> keywords = splitToList(module.getKeywords());
            List<String> negatives = splitToList(module.getNegativeKeywords());

            // 过滤排除词
            boolean containsNegative = negatives.stream().anyMatch(text::contains);
            if (containsNegative) {
                continue;
            }

            // 关键词匹配
            boolean containsKeyword = keywords.stream().anyMatch(text::contains);
            if (containsKeyword) {
                matched.add(module);
            }
        }

        if (matched.isEmpty()) {
            return null;
        }

        // 根据权重排序（权重越大优先）
        return matched.stream()
                .sorted(Comparator.comparing(PromptModulesEntity::getWeight, Comparator.nullsLast(Comparator.reverseOrder())))
                .findFirst()
                .orElse(null);
    }

    /**
     * 将逗号分隔字符串转为去重后的列表
     */
    private List<String> splitToList(String str) {
        if (!StringUtils.hasText(str)) {
            return Collections.emptyList();
        }
        return Arrays.stream(str.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .distinct()
                .collect(Collectors.toList());
    }

}
