package com.example.myapplication.service;

import android.content.Context;
import android.util.Log;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary;
import java.util.ArrayList;
import java.util.List;

public class EnhancedKeywordClassifier {
    private final Context context;
    private boolean hanLPInitialized = false;

    public static class Result {
        public String bestId = "";
        public String bestTitle = "";
        public double confidence = 0.0;
        public boolean isSegmented = false;
        public List<Object> topCandidates = new ArrayList<>();
    }

    public static class ClassificationResult {
        public String category = "";
        public String chapter = "";
        public String bestId = "";
        public String bestTitle = "";
        public double confidence = 0.0;
        public boolean isSegmented = false;
        public List<Object> topCandidates = new ArrayList<>();
    }

    public EnhancedKeywordClassifier(Context ctx) {
        this.context = ctx == null ? null : ctx.getApplicationContext();
        try {
            List<Term> testSegment = HanLP.segment("测试HanLP");
            hanLPInitialized = true;
            Log.i("HanLP", "HanLP初始化成功，分词测试：" + testSegment.toString());
        } catch (Throwable e) {
            Log.w("HanLP", "HanLP初始化失败，将使用基础分类: " + String.valueOf(e));
            hanLPInitialized = false;
        }
    }

    public EnhancedKeywordClassifier() {
        this(null);
    }

    public ClassificationResult classifyWithSegmentation(String text) {
        Result base = performBasicClassification(text);
        ClassificationResult resultOut = new ClassificationResult();
        resultOut.bestId = base.bestId;
        resultOut.bestTitle = base.bestTitle;
        resultOut.category = base.bestTitle;
        resultOut.chapter = base.bestTitle;
        resultOut.confidence = base.confidence;
        resultOut.isSegmented = false;
        resultOut.topCandidates = base.topCandidates;
        if (text == null || text.trim().isEmpty()) {
            resultOut.bestTitle = "默认分类";
            resultOut.category = resultOut.bestTitle;
            resultOut.chapter = resultOut.bestTitle;
            resultOut.confidence = 0.0;
            return resultOut;
        }
        if (hanLPInitialized && base.confidence < 0.7) {
            try {
                List<Term> terms = HanLP.segment(text);
                StringBuilder segmentedText = new StringBuilder();
                StringBuilder keywordsText = new StringBuilder();
                for (Term term : terms) {
                    String word = term.word;
                    String nature = term.nature != null ? term.nature.toString() : "";
                    if (word.length() > 1 && !CoreStopWordDictionary.contains(word)) {
                        segmentedText.append(word).append(" ");
                        if (nature.startsWith("n") || nature.startsWith("v") || nature.startsWith("a")) {
                            keywordsText.append(word).append(" ");
                        }
                    }
                }
                String enhancedText = segmentedText.toString() + " " + keywordsText.toString();
                Result segmentedBase = performBasicClassification(enhancedText);
                ClassificationResult segmentedOut = new ClassificationResult();
                segmentedOut.bestId = segmentedBase.bestId;
                segmentedOut.bestTitle = segmentedBase.bestTitle;
                segmentedOut.category = segmentedBase.bestTitle;
                segmentedOut.chapter = segmentedBase.bestTitle;
                segmentedOut.confidence = segmentedBase.confidence;
                segmentedOut.isSegmented = true;
                segmentedOut.topCandidates = segmentedBase.topCandidates;
                if (segmentedOut.confidence > resultOut.confidence) {
                    segmentedOut.confidence = Math.min(0.95, segmentedOut.confidence * 1.2);
                    return segmentedOut;
                }
            } catch (Throwable e) {
                Log.w("HanLP", "HanLP分词失败，使用基础分类: " + String.valueOf(e));
            }
        }
        return resultOut;
    }

    private Result performBasicClassification(String text) {
        Result result = new Result();
        if (text == null) return result;
        String lowerText = text.toLowerCase();
        if (lowerText.contains("程序") || lowerText.contains("java") || lowerText.contains("方法") || lowerText.contains("类")) {
            result.bestTitle = "程序设计";
            result.confidence = 0.8;
        } else if (lowerText.contains("数据结构") || lowerText.contains("数组") || lowerText.contains("链表") || lowerText.contains("栈") || lowerText.contains("队列")) {
            result.bestTitle = "数据结构";
            result.confidence = 0.75;
        } else if (lowerText.contains("高等数学") || lowerText.contains("微积分") || lowerText.contains("导数") || lowerText.contains("积分") || lowerText.contains("极限")) {
            result.bestTitle = "高等数学";
            result.confidence = 0.7;
        } else if (lowerText.contains("人工智能") || lowerText.contains("ai") || lowerText.contains("机器学习") || lowerText.contains("深度学习")) {
            result.bestTitle = "人工智能";
            result.confidence = 0.8;
        } else if (lowerText.contains("物联网") || lowerText.contains("iot") || lowerText.contains("传感器") || lowerText.contains("rfid")) {
            result.bestTitle = "物联网";
            result.confidence = 0.75;
        } else if (lowerText.contains("英语") || lowerText.contains("english")) {
            result.bestTitle = "大学英语";
            result.confidence = 0.6;
        } else if (lowerText.contains("数据库") || lowerText.contains("sql") || lowerText.contains("关系模型")) {
            result.bestTitle = "数据库系统";
            result.confidence = 0.75;
        } else if (lowerText.contains("机器人") || lowerText.contains("robot") || lowerText.contains("robotics")) {
            result.bestTitle = "第1章 机器人学概述";
            result.confidence = 0.7;
        } else {
            result.bestTitle = "程序设计";
            result.confidence = 0.5;
        }
        return result;
    }
}