package org.dromara.ai.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.knowledge.domain.vo.KnowledgeSearchResultVo;
import org.dromara.knowledge.service.KnowledgeInfoService;
import org.dromara.knowledge.service.KnowledgeVectorService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 简化的AI服务
 * 主要功能：调用knowledge模块进行知识检索
 *
 * @author pengles
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SimpleAiService {

    private final KnowledgeInfoService knowledgeInfoService;
    private final KnowledgeVectorService knowledgeVectorService;

    /**
     * 基于知识库的问答
     *
     * @param knowledgeId 知识库ID
     * @param question    用户问题
     * @param limit       返回结果数量限制
     * @return AI回答
     */
    public String askWithKnowledge(String knowledgeId, String question, Integer limit) {
        log.info("基于知识库问答 - 知识库ID: {}, 问题: {}", knowledgeId, question);

        try {
            // 1. 从知识库搜索相关内容
            List<KnowledgeSearchResultVo> searchResults = knowledgeInfoService.searchKnowledge(
                    knowledgeId, question, limit != null ? limit : 5
            );

            if (searchResults.isEmpty()) {
                return "抱歉，在知识库中没有找到相关信息。";
            }

            // 2. 构建回答
            StringBuilder answer = new StringBuilder();
            answer.append("根据知识库搜索结果，为您提供以下信息：\n\n");

            for (int i = 0; i < searchResults.size(); i++) {
                KnowledgeSearchResultVo result = searchResults.get(i);
                answer.append(String.format("%d. %s\n", i + 1, result.getContent()));
                if (result.getSimilarityScore() != null) {
                    answer.append(String.format("   (相关度: %.2f)\n", result.getSimilarityScore()));
                }
                answer.append("\n");
            }

            return answer.toString();

        } catch (Exception e) {
            log.error("知识库问答失败", e);
            return "抱歉，处理您的问题时出现错误，请稍后重试。";
        }
    }

    /**
     * 向量相似度搜索
     *
     * @param knowledgeId 知识库ID
     * @param queryText   查询文本
     * @param modelName   模型名称
     * @param topK        返回前K个结果
     * @param threshold   相似度阈值
     * @return 搜索结果
     */
    public List<KnowledgeSearchResultVo> vectorSearch(String knowledgeId, String queryText,
                                                      String modelName, Integer topK, Double threshold) {
        log.info("向量搜索 - 知识库ID: {}, 查询: {}, 模型: {}", knowledgeId, queryText, modelName);

        try {
            return knowledgeVectorService.vectorSimilaritySearch(
                    knowledgeId, queryText, modelName,
                    topK != null ? topK : 5,
                    threshold != null ? threshold : 0.7
            );
        } catch (Exception e) {
            log.error("向量搜索失败", e);
            return List.of();
        }
    }

    /**
     * 获取知识库统计信息
     *
     * @param knowledgeId 知识库ID
     * @return 统计信息
     */
    public Map<String, Object> getKnowledgeStats(String knowledgeId) {
        log.info("获取知识库统计信息 - 知识库ID: {}", knowledgeId);

        try {
            Map<String, Object> stats = knowledgeVectorService.getVectorStatistics(knowledgeId);
            if (stats == null) {
                stats = new HashMap<>();
            }

            // 添加知识库状态信息
            var status = knowledgeInfoService.getKnowledgeStatus(knowledgeId);
            if (status != null) {
                stats.put("status", status);
            }

            return stats;

        } catch (Exception e) {
            log.error("获取知识库统计信息失败", e);
            return Map.of("error", "获取统计信息失败");
        }
    }

    /**
     * 检查模型是否可用
     *
     * @param modelName 模型名称
     * @return 是否可用
     */
    public boolean isModelAvailable(String modelName) {
        try {
            return knowledgeVectorService.isModelAvailable(modelName);
        } catch (Exception e) {
            log.error("检查模型可用性失败: {}", modelName, e);
            return false;
        }
    }

    /**
     * 获取可用的模型列表
     *
     * @return 模型列表
     */
    public List<String> getAvailableModels() {
        try {
            return knowledgeVectorService.getAvailableModels();
        } catch (Exception e) {
            log.error("获取可用模型列表失败", e);
            return List.of();
        }
    }
}