package com.warmer.base.service;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.tokenizer.StandardTokenizer;
import org.springframework.stereotype.Service;

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

/**
 * 关键字提取服务
 * 
 * @author tanc
 */
@Service
public class KeywordExtractionService {
    
    // 停用词集合
    private static final Set<String> STOP_WORDS = new HashSet<>(Arrays.asList(
        "的", "了", "在", "是", "我", "有", "和", "就", "不", "人", "都", "一", "一个", "上", "也", "很", "到", "说", "要", "去", "你", "会", "着", "没有", "看", "好", "自己", "这"
    ));
    
    // 故障相关的重要词性
    private static final Set<String> IMPORTANT_POS = new HashSet<>(Arrays.asList(
        "n", "nr", "ns", "nt", "nz", "nl", "ng", "v", "vn", "a", "an"
    ));
    
    /**
     * 从故障描述中提取关键字
     * 
     * @param text 故障描述文本
     * @return 关键字列表，按重要性排序
     */
    // 强化自定义词典，保证行业术语被识别为稳定分词
    static {
        try {
            // 先设置 IOAdapter：从 jar 的 classpath 读取 HanLP 资源
            com.hankcs.hanlp.HanLP.Config.IOAdapter = new com.hankcs.hanlp.corpus.io.ResourceIOAdapter();

            // 强化自定义词典，保证行业术语被识别为稳定分词
            com.hankcs.hanlp.dictionary.CustomDictionary.add("冷轧", "nz 1000");
            com.hankcs.hanlp.dictionary.CustomDictionary.add("热轧", "nz 1000");
            com.hankcs.hanlp.dictionary.CustomDictionary.add("轴承座", "n 1000");
            com.hankcs.hanlp.dictionary.CustomDictionary.add("轴承", "n 1000");
        } catch (Exception ignored) {}
    }
    public List<String> extractKeywords(String text) {
        if (text == null || text.trim().isEmpty()) {
            return new ArrayList<>();
        }
        
        // 使用HanLP进行分词和词性标注
        List<Term> terms = StandardTokenizer.segment(text);
        
        // 提取关键词
        Map<String, Integer> keywordCount = new HashMap<>();
        
        for (Term term : terms) {
            String word = term.word.trim();
            String nature = term.nature.toString();
            
            // 过滤条件：长度大于1，不是停用词，词性重要
            if (word.length() > 1 && 
                !STOP_WORDS.contains(word) && 
                IMPORTANT_POS.contains(nature)) {
                
                keywordCount.put(word, keywordCount.getOrDefault(word, 0) + 1);
            }
        }
        
        // 按词频排序，返回关键字列表
        return keywordCount.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .map(Map.Entry::getKey)
                .limit(10) // 最多返回10个关键字
                .collect(Collectors.toList());
    }
    
    /**
     * 提取关键字并返回详细信息
     * 
     * @param text 故障描述文本
     * @return 关键字详细信息
     */
    public List<KeywordInfo> extractKeywordsWithInfo(String text) {
        if (text == null || text.trim().isEmpty()) {
            return new ArrayList<>();
        }
        
        List<Term> terms = StandardTokenizer.segment(text);
        Map<String, KeywordInfo> keywordMap = new HashMap<>();
        
        for (Term term : terms) {
            String word = term.word.trim();
            String nature = term.nature.toString();
            
            if (word.length() > 1 && 
                !STOP_WORDS.contains(word) && 
                IMPORTANT_POS.contains(nature)) {
                
                KeywordInfo info = keywordMap.getOrDefault(word, new KeywordInfo(word, nature));
                info.incrementCount();
                keywordMap.put(word, info);
            }
        }
        
        return keywordMap.values().stream()
                .sorted((a, b) -> Integer.compare(b.getCount(), a.getCount()))
                .limit(10)
                .collect(Collectors.toList());
    }
    
    /**
     * 关键字信息类
     */
    public static class KeywordInfo {
        private String keyword;
        private String partOfSpeech;
        private int count;
        
        public KeywordInfo(String keyword, String partOfSpeech) {
            this.keyword = keyword;
            this.partOfSpeech = partOfSpeech;
            this.count = 1;
        }
        
        public void incrementCount() {
            this.count++;
        }
        
        // Getters and Setters
        public String getKeyword() { return keyword; }
        public void setKeyword(String keyword) { this.keyword = keyword; }
        public String getPartOfSpeech() { return partOfSpeech; }
        public void setPartOfSpeech(String partOfSpeech) { this.partOfSpeech = partOfSpeech; }
        public int getCount() { return count; }
        public void setCount(int count) { this.count = count; }
    }
}