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

import cn.hutool.core.collection.CollectionUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.seer.teach.admin.request.GenerateSimilarQuestionReq;
import com.seer.teach.admin.response.ExampleQuestionsResp;
import com.seer.teach.admin.response.QuestionOptionsResp;
import com.seer.teach.admin.service.ExampleQuestionGenerationService;
import com.seer.teach.admin.util.PromptBuilder;
import com.seer.teach.teacher.module.entity.ExampleQuestionsEntity;
import com.seer.teach.teacher.module.entity.KnowledgePointEntity;
import com.seer.teach.teacher.service.ExampleQuestionsService;
import com.seer.teach.teacher.service.KnowledgePointQueryService;
import com.seer.teach.teacher.service.platform.LlmResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 题目生成服务实现类
 * </p>
 *
 * @author ZS
 * @since 2025-10-31
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ExampleQuestionGenerationServiceImpl extends AbstractGenerationService<ExampleQuestionsResp, GenerateSimilarQuestionReq, ExampleQuestionsEntity> implements ExampleQuestionGenerationService {

    private final ExampleQuestionsService exampleQuestionsService;

    private final KnowledgePointQueryService knowledgePointQueryService;

    /**
     * 根据示例题目生成示例题目
     *
     * @param req 生成题目参数
     * @return 生成的题目列表
     */
    @Override
    public List<ExampleQuestionsResp> generateSimilarQuestions(GenerateSimilarQuestionReq req) {
        log.info("开始根据示例题目生成示例题目，请求参数: {}", req);

        // 1. 根据示例题目id查询对应的知识点和示例题目
        ExampleQuestionsEntity exampleQuestion = exampleQuestionsService.getById(req.getExampleQuestionId());
        if (Objects.isNull(exampleQuestion)) {
            log.warn("未找到示例题目，ID: {}", req.getExampleQuestionId());
            return Collections.emptyList();
        }

        KnowledgePointEntity knowledgePoint = knowledgePointQueryService.getKnowledgePointByKnowId(exampleQuestion.getKnowId());
        if (Objects.isNull(knowledgePoint)) {
            log.warn("未找到知识点，ID: {}", exampleQuestion.getKnowId());
            return Collections.emptyList();
        }
        // 3. 调用大模型生成题目
        List<ExampleQuestionsResp> generatedQuestions = callLLMToGenerateQuestions(exampleQuestion, knowledgePoint, req.getCount(), req.getScenarioCode(), req.getUserId());
        if (CollectionUtil.isNotEmpty(generatedQuestions)) {
            generatedQuestions.forEach(item -> {
                item.setKnowId(knowledgePoint.getId());
                item.setType(exampleQuestion.getType());
            });
        }
        log.info("生成类似题目完成，共生成 {} 道题目", generatedQuestions.size());
        return generatedQuestions;
    }
    


    /**
     * 调用大模型生成示例题目
     *
     * @param exampleQuestion 示例题目
     * @param knowledgePoint  知识点
     * @param count           生成数量
     * @return 生成的题目列表
     */
    private List<ExampleQuestionsResp> callLLMToGenerateQuestions(ExampleQuestionsEntity exampleQuestion,
                                                                  KnowledgePointEntity knowledgePoint,
                                                                  Integer count,
                                                                  String scenarioCode,
                                                                  Integer userId) {
        // 构建提示词
        String prompt = PromptBuilder.buildPromptForQuestionGeneration(exampleQuestion, knowledgePoint, count);

        log.info("调用大模型生成题目，提示词长度: {}", prompt.length());

        // 调用大模型API生成题目
        LlmResponse result = callLLM(scenarioCode, prompt, new HashMap<>(), userId);

        if (Objects.isNull(result)) {
            log.warn("调用大模型生成题目失败，返回结果为空");
            return Collections.emptyList();
        }

        List<ExampleQuestionsResp> questions = new ArrayList<>();
        for (LlmResponse.Choice choice : result.getChoices()) {
            LlmResponse.Message message = choice.getMessage();
            if (Objects.isNull(message)) {
                log.warn("调用大模型生成题目失败，返回结果中 'message' 为空");
                continue;
            }
            String content = message.getContent();
            List<ExampleQuestionsResp> resultList = parseLLMResponse(content,questionNode ->{
                ExampleQuestionsResp resp = new ExampleQuestionsResp();
                // 解析基本字段
                resp.setQuestion(getStringValue(questionNode, "question"));
                resp.setAnswer(parseAnswer(questionNode.has("answer") ? questionNode.get("answer") : null));
                resp.setSolution(getStringValue(questionNode, "solution"));
                
                if (questionNode.has("isNeedImage")) {
                    resp.setIsNeedImage(questionNode.get("isNeedImage").asInt());
                }
                
                // 解析选项（如果有）
                if (questionNode.has("options") && questionNode.get("options").isArray()) {
                    List<QuestionOptionsResp> optionsResp = new ArrayList<>();
                    JsonNode optionsArray = questionNode.get("options");

                    for (JsonNode optionNode : optionsArray) {
                        QuestionOptionsResp optionResp = new QuestionOptionsResp();
                        optionResp.setContent(getStringValue(optionNode, "content"));
                        optionResp.setSort(getIntValue(optionNode, "sort"));
                        optionsResp.add(optionResp);
                    }
                    resp.setOptions(optionsResp);
                }
                return resp;
            });
            questions.addAll(resultList);
        }
        log.info("大模型响应处理完成，生成 {} 道题目", questions.size());
        return questions;
    }


    /**
     * 解析答案字段，支持字符串和数组两种格式
     *
     * @param answerNode 答案节点
     * @return 处理后的答案字符串
     */
    private String parseAnswer(JsonNode answerNode) {
        if (answerNode == null || answerNode.isNull()) {
            return "";
        }

        // 如果是字符串，直接返回
        if (answerNode.isTextual()) {
            return answerNode.asText();
        }

        // 如果是数组，用逗号连接
        if (answerNode.isArray()) {
            List<String> answers = new ArrayList<>();
            for (JsonNode node : answerNode) {
                if (node.isTextual()) {
                    answers.add(node.asText());
                }
            }
            return String.join(",", answers);
        }

        // 其他情况，转换为字符串
        return answerNode.asText();
    }
    
    @Override
    protected String getTaskIdFromRequest(GenerateSimilarQuestionReq request) {
        return null;
    }
}