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

import cn.hutool.core.collection.CollectionUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seer.teach.admin.request.KnowledgePointCheckReq;
import com.seer.teach.admin.response.KnowledgePointCheckResp;
import com.seer.teach.teacher.service.AiModelCallService;
import com.seer.teach.admin.service.KnowledgePointCheckService;
import com.seer.teach.teacher.service.platform.LlmResponse;
import com.seer.teach.admin.util.PromptBuilder;
import com.seer.teach.common.enums.AiScenarioCodeEnum;
import com.seer.teach.teacher.module.entity.KnowSummaryEntity;
import com.seer.teach.teacher.module.entity.KnowledgePointEntity;
import com.seer.teach.teacher.module.entity.MaterialEntity;
import com.seer.teach.teacher.service.KnowSummaryService;
import com.seer.teach.teacher.service.KnowledgePointQueryService;
import com.seer.teach.teacher.service.KnowledgePointService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 知识点检查服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class KnowledgePointCheckServiceImpl implements KnowledgePointCheckService {

    private final KnowledgePointService knowledgePointService;
    
    private final KnowledgePointQueryService knowledgePointQueryService;
    
    private final KnowSummaryService knowSummaryService;
    
    private final AiModelCallService aiModelCallService;

    /**
     * 检查知识点内容是否正确和超纲
     *
     * @param req 知识点检查请求参数
     * @return 知识点检查结果
     */
    @Override
    public KnowledgePointCheckResp checkKnowledgePoint(KnowledgePointCheckReq req) {
        log.info("开始检查知识点内容，知识点ID: {}", req.getKnowledgePointId());
        
        // 1. 查询知识点信息
        KnowledgePointEntity knowledgePoint = knowledgePointService.getById(req.getKnowledgePointId());
        if (knowledgePoint == null) {
            throw new IllegalArgumentException("知识点不存在");
        }
        
        // 2. 查询知识点摘要
        KnowSummaryEntity summary = knowSummaryService.getOneByKnowId(req.getKnowledgePointId());
        Collection<MaterialEntity> materials = knowledgePointQueryService.getMaterialListByKnowId(req.getKnowledgePointId());
        if (CollectionUtil.isEmpty(materials)) {
            log.warn("知识点下没有教材，请先添加教材");
            return null;
        }
        Collection<Integer> gradeIds = materials.stream().map(MaterialEntity::getGradeId).collect(Collectors.toSet());
        // 3. 构建提示词
        String prompt = PromptBuilder.buildCheckPrompt(knowledgePoint, summary,gradeIds);
        log.info("构建提示词: {}", prompt);
        
        // 4. 调用大模型进行知识点检查
        LlmResponse result = aiModelCallService.callModel(AiScenarioCodeEnum.KNOWLEDGE_POINT_CHECK.getCode(), prompt, new HashMap<>(), null);

        if (Objects.isNull(result)) {
            log.warn("调用大模型检查知识点失败，返回结果为空");
            throw new RuntimeException("调用大模型检查知识点失败");
        }

        // 5. 解析大模型返回结果
        return parseLLMResponse(result, req.getKnowledgePointId(), knowledgePoint.getKnowledgePointName());
    }

    /**
     * 解析大模型响应（用于知识点检查场景）
     *
     * @param result 大模型响应结果
     * @param knowledgePointId 知识点ID
     * @param knowledgePointName 知识点名称
     * @return 检查结果
     */
    private KnowledgePointCheckResp parseLLMResponse(LlmResponse result, Integer knowledgePointId, String knowledgePointName) {
        KnowledgePointCheckResp resp = new KnowledgePointCheckResp();
        resp.setKnowledgePointId(knowledgePointId);
        resp.setKnowledgePointName(knowledgePointName);

        try {
            for (LlmResponse.Choice choice : result.getChoices()) {
                LlmResponse.Message message = choice.getMessage();
                if (Objects.isNull(message)) {
                    log.warn("大模型响应中 'message' 为空");
                    continue;
                }

                String content = message.getContent();
                log.info("大模型响应内容: {}", content);

                // 尝试解析内容中的JSON对象
                content = content.trim();
                if (content.startsWith("```json")) {
                    content = content.substring(7, content.length() - 3).trim();
                } else if (content.startsWith("```")) {
                    content = content.substring(3, content.length() - 3).trim();
                }

                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readTree(content);

                resp.setIsCorrect(jsonNode.has("isCorrect") ? jsonNode.get("isCorrect").asBoolean() : true);
                resp.setIsOutOfScope(jsonNode.has("isOutOfScope") ? jsonNode.get("isOutOfScope").asBoolean() : false);
                resp.setOutOfScopeReason(jsonNode.has("outOfScopeReason") && !jsonNode.get("outOfScopeReason").isNull() ? jsonNode.get("outOfScopeReason").asText() : null);
                resp.setSuggestedKnowledgePointName(jsonNode.has("suggestedKnowledgePointName") && !jsonNode.get("suggestedKnowledgePointName").isNull() ? jsonNode.get("suggestedKnowledgePointName").asText() : null);
                resp.setSuggestedSummary(jsonNode.has("suggestedSummary") && !jsonNode.get("suggestedSummary").isNull() ? jsonNode.get("suggestedSummary").asText() : null);

                // 解析示例题目
                if (jsonNode.has("exampleQuestions") && jsonNode.get("exampleQuestions").isArray()) {
                    List<KnowledgePointCheckResp.ExampleQuestion> exampleQuestions = new ArrayList<>();
                    JsonNode questionsArray = jsonNode.get("exampleQuestions");

                    for (JsonNode questionNode : questionsArray) {
                        KnowledgePointCheckResp.ExampleQuestion exampleQuestion = new KnowledgePointCheckResp.ExampleQuestion();
                        if (!questionNode.has("type")) {
                            log.warn("示例题目类型为空");
                            continue;
                        }
                        exampleQuestion.setType(questionNode.get("type").asInt());
                        exampleQuestion.setQuestion(
                                questionNode.has("question") ? questionNode.get("question").asText() : "");
                        exampleQuestion.setAnswer(
                                questionNode.has("answer") ? questionNode.get("answer").asText() : "");
                        exampleQuestion.setExplanation(
                                questionNode.has("explanation") ? questionNode.get("explanation").asText() : "");

                        // 解析选项（如果有）
                        if (questionNode.has("options") && questionNode.get("options").isArray()) {
                            List<KnowledgePointCheckResp.QuestionOption> options = new ArrayList<>();
                            JsonNode optionsArray = questionNode.get("options");
                            for (JsonNode optionNode : optionsArray) {
                                KnowledgePointCheckResp.QuestionOption option = new KnowledgePointCheckResp.QuestionOption();
                                option.setContent(optionNode.asText());
                                // 简化处理，实际排序可能需要额外信息
                                option.setSort(options.size());
                                options.add(option);
                            }
                            exampleQuestion.setOptions(options);
                        }

                        exampleQuestions.add(exampleQuestion);
                    }
                    resp.setExampleQuestions(exampleQuestions);
                } else {
                    resp.setExampleQuestions(Collections.emptyList());
                }
            }
        } catch (Exception e) {
            log.error("解析大模型响应时发生异常", e);
            // 设置默认值
            resp.setIsCorrect(true);
            resp.setIsOutOfScope(false);
            resp.setOutOfScopeReason(null);
            resp.setSuggestedKnowledgePointName(null);
            resp.setSuggestedSummary(null);
            resp.setExampleQuestions(Collections.emptyList());
        }

        log.info("知识点检查完成，结果: {}", resp);
        return resp;
    }


}