package net.micode.myapplication.service;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.common.Term;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.regex.Pattern;

public class TextProcessor {
    
    // 常见停用词列表
    private static final String[] STOP_WORDS = {
        "的", "了", "在", "是", "我", "有", "和", "就", "不", "人", "都", "一", "一个", "上", "也", "很", "到", "说", "要", "去", "你", "会", "着", "没有", "看", "好", "自己", "这"
    };
    
    // 标点符号正则表达式
    private static final Pattern PUNCTUATION_PATTERN = Pattern.compile("[\\p{Punct}\\s]+");
    
    /**
     * 预处理文本：去除标点符号、转换为小写、去除多余空格
     */
    public String preprocessText(String text) {
        if (text == null || text.trim().isEmpty()) {
            return "";
        }
        
        // 去除标点符号和特殊字符
        text = PUNCTUATION_PATTERN.matcher(text).replaceAll(" ");
        
        // 去除多余空格
        text = text.replaceAll("\\s+", " ").trim();
        
        return text.toLowerCase();
    }
    
    /**
     * 提取关键词：使用HanLP进行分词并过滤停用词
     */
    public List<String> extractKeywords(String text, int maxKeywords) {
        List<String> keywords = new ArrayList<>();
        
        if (text == null || text.trim().isEmpty()) {
            return keywords;
        }
        
        try {
            // 使用HanLP进行分词
            List<Term> terms = HanLP.segment(text);
            
            // 统计词频
            Map<String, Integer> wordFrequency = new HashMap<>();
            for (Term term : terms) {
                String word = term.word.trim();
                if (word.length() >= 2 && !isStopWord(word)) { // 只保留长度>=2的词
                    Integer count = wordFrequency.get(word);
                    wordFrequency.put(word, count == null ? 1 : count + 1);
                }
            }
            
            // 按词频排序并返回前maxKeywords个词
            List<Map.Entry<String, Integer>> entries = new ArrayList<>(wordFrequency.entrySet());
            Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
                @Override
                public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) {
                    return b.getValue().compareTo(a.getValue());
                }
            });
            for (int i = 0; i < Math.min(maxKeywords, entries.size()); i++) {
                keywords.add(entries.get(i).getKey());
            }
                    
        } catch (Exception e) {
            e.printStackTrace();
            // 如果HanLP失败，使用简单的空格分割
            String[] words = text.split("\\s+");
            for (String word : words) {
                if (word.length() >= 2 && !isStopWord(word)) {
                    keywords.add(word);
                    if (keywords.size() >= maxKeywords) {
                        break;
                    }
                }
            }
        }
        
        return keywords;
    }
    
    /**
     * 提取文本特征：包括关键词、词频等
     */
    public Map<String, Object> extractTextFeatures(String text) {
        Map<String, Object> features = new HashMap<>();
        
        if (text == null || text.trim().isEmpty()) {
            return features;
        }
        
        String processedText = preprocessText(text);
        List<String> keywords = extractKeywords(processedText, 20);
        
        // 计算词频
        Map<String, Integer> wordFrequency = new HashMap<>();
        String[] words = processedText.split("\\s+");
        for (String word : words) {
            if (word.length() >= 2 && !isStopWord(word)) {
                Integer count = wordFrequency.get(word);
                wordFrequency.put(word, count == null ? 1 : count + 1);
            }
        }
        
        features.put("text", processedText);
        features.put("keywords", keywords);
        features.put("wordFrequency", wordFrequency);
        features.put("wordCount", words.length);
        features.put("uniqueWordCount", wordFrequency.size());
        
        return features;
    }
    
    /**
     * 计算两个文本的相似度（基于关键词重叠）
     */
    public double calculateTextSimilarity(String text1, String text2) {
        if (text1 == null || text2 == null || text1.isEmpty() || text2.isEmpty()) {
            return 0.0;
        }
        
        List<String> keywords1 = extractKeywords(preprocessText(text1), 10);
        List<String> keywords2 = extractKeywords(preprocessText(text2), 10);
        
        if (keywords1.isEmpty() || keywords2.isEmpty()) {
            return 0.0;
        }
        
        // 计算交集
        List<String> intersection = new ArrayList<>(keywords1);
        intersection.retainAll(keywords2);
        
        // 计算并集
        List<String> union = new ArrayList<>(keywords1);
        for (String keyword : keywords2) {
            if (!union.contains(keyword)) {
                union.add(keyword);
            }
        }
        
        // Jaccard相似度
        return (double) intersection.size() / union.size();
    }
    
    /**
     * 计算关键词匹配分数
     */
    public double calculateKeywordMatchScore(String text, List<String> targetKeywords) {
        if (text == null || targetKeywords == null || targetKeywords.isEmpty()) {
            return 0.0;
        }
        
        String processedText = preprocessText(text);
        List<String> textKeywords = extractKeywords(processedText, 50); // 提取更多关键词用于匹配
        
        int matchCount = 0;
        for (String targetKeyword : targetKeywords) {
            String processedTarget = preprocessText(targetKeyword);
            if (textKeywords.contains(processedTarget) || processedText.contains(processedTarget)) {
                matchCount++;
            }
        }
        
        return (double) matchCount / targetKeywords.size();
    }
    
    /**
     * 判断是否为停用词
     */
    private boolean isStopWord(String word) {
        if (word == null || word.trim().isEmpty()) {
            return true;
        }
        
        for (String stopWord : STOP_WORDS) {
            if (stopWord.equals(word)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 提取文本中的数字信息（章节号等）
     */
    public List<Integer> extractNumbers(String text) {
        List<Integer> numbers = new ArrayList<>();
        if (text == null || text.trim().isEmpty()) {
            return numbers;
        }
        
        Pattern pattern = Pattern.compile("\\d+");
        java.util.regex.Matcher matcher = pattern.matcher(text);
        
        while (matcher.find()) {
            try {
                numbers.add(Integer.parseInt(matcher.group()));
            } catch (NumberFormatException e) {
                // 忽略解析错误的数字
            }
        }
        
        return numbers;
    }
}