package top.tqx.demo_1.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import top.tqx.demo_1.dto.ExamGenerateRequest;
import top.tqx.demo_1.dto.ExamGenerateResponse;
import top.tqx.demo_1.entity.Question;
import top.tqx.demo_1.service.QuestionSaveService;
import top.tqx.demo_1.service.QuestionService;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class QuestionSaveServiceImpl implements QuestionSaveService {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private QuestionService questionService;

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void saveQuestionsToDatabase(ExamGenerateResponse response, ExamGenerateRequest request) {
        try {
            List<ExamGenerateRequest.Question> questions = response.getQuestions();
            List<String> tagList = request.getTags();
            JsonNode tagsNode = null;
            if (tagList != null && !tagList.isEmpty()) {
                try {
                    tagsNode = objectMapper.readTree(JSON.toJSONString(tagList));
                } catch (Exception e) {
                    log.warn("解析tags失败: {}", e.getMessage());
                }
            }

            String knowledgeBasePath = null;
            if (request.getCollection() != null) {
                if (request.getCollection() instanceof String) {
                    knowledgeBasePath = (String) request.getCollection();
                }
            } else if (request.getCollectionName() != null && !request.getCollectionName().isEmpty()) {
                knowledgeBasePath = request.getCollectionName();
            }

            Map<String, BigDecimal> questionScores = request.getQuestionScores();
            if (questionScores != null && !questionScores.isEmpty()) {
                log.info("使用自定义题型分数配置: {}", questionScores);
            } else {
                log.info("未配置自定义题型分数，将使用默认分数");
            }

            Integer sourceChunksUsed = response.getSourceChunksUsed();
            int successCount = 0;
            int failCount = 0;

            Long fileId = request.getFileId();
            log.info("文件ID: {}", fileId);

            for (ExamGenerateRequest.Question question : questions) {
                try {
                    Question questionEntity = convertToQuestionEntity(question, tagsNode, knowledgeBasePath, sourceChunksUsed, questionScores, fileId);
                    boolean saved = questionService.saveQuestion(questionEntity);
                    if (saved) {
                        successCount++;
                        log.info("题目已保存到数据库: questionId={}, questionType={}, score={}, knowledgeBasePath={}, documentId={}",
                                questionEntity.getQuestionId(), questionEntity.getQuestionType(), questionEntity.getScore(), knowledgeBasePath, questionEntity.getDocumentId());
                    } else {
                        failCount++;
                        log.warn("题目保存失败: questionType={}", question.getQuestionType());
                    }
                } catch (Exception e) {
                    failCount++;
                    log.error("保存单个题目失败: questionType={}, error={}",
                            question.getQuestionType(), e.getMessage());
                }
            }

            log.info("题目保存完成: 总数={}, 成功={}, 失败={}",
                    questions.size(), successCount, failCount);

            if (failCount > 0 && successCount == 0) {
                throw new RuntimeException("所有题目保存失败，共" + failCount + "道题");
            }
        } catch (Exception e) {
            log.error("保存题目到数据库失败", e);
            throw e;
        }
    }

    private Question convertToQuestionEntity(ExamGenerateRequest.Question question, JsonNode tagsNode, String knowledgeBasePath, Integer sourceChunksUsed, Map<String, BigDecimal> questionScores, Long fileId) {
        Question entity = new Question();
        entity.setQuestionId(java.util.UUID.randomUUID().toString());
        
        String questionType = question.getQuestionType();
        if (questionType == null || questionType.isEmpty()) {
            log.warn("AI返回的 questionType 为空，设置为默认值 single_choice");
            questionType = "single_choice";
        }
        entity.setQuestionType(questionType);
        entity.setDifficulty(question.getDifficulty() != null ? question.getDifficulty() : 3);
        entity.setTags(tagsNode);
        entity.setScore(calculateScore(questionType, question.getScore(), questionScores));
        entity.setVersion("1.0");
        entity.setStatus("pending");
        entity.setKnowledgeBasePath(knowledgeBasePath);
        entity.setSourceChunksUsed(sourceChunksUsed);
        
        if (fileId != null) {
            entity.setDocumentId(String.valueOf(fileId));
            log.info("设置 documentId 为 fileId: {}", fileId);
        } else if (question.getSourceTrace() != null && question.getSourceTrace().getDocumentName() != null) {
            entity.setDocumentId(question.getSourceTrace().getDocumentName());
            log.info("设置 documentId 为 documentName: {}", question.getSourceTrace().getDocumentName());
        } else {
            log.warn("documentId 未设置: fileId={}, sourceTrace={}", fileId, question.getSourceTrace());
        }
        
        // 初始化统计字段，避免数据库约束问题
        entity.setExamCount(0);
        entity.setCorrectCount(0);
        entity.setLastExamTime(null);
        
        entity.setCreatedAt(LocalDateTime.now());
        entity.setUpdatedAt(LocalDateTime.now());

        log.info("=== 题目数据 ===");
        log.info("questionType: {}", questionType);
        log.info("difficulty: {}", entity.getDifficulty());
        log.info("knowledgeBasePath: {}", knowledgeBasePath);

        ExamGenerateRequest.QuestionContent content = question.getContent();
        if (content != null && content.getStem() != null && !content.getStem().isEmpty()) {
            try {
                String contentJson = JSON.toJSONString(content);
                log.info("AI返回的题目内容: {}", contentJson);
                entity.setContent(objectMapper.readTree(contentJson));
                log.info("解析后的 content: {}", entity.getContent());
            } catch (Exception e) {
                log.error("解析题目内容失败: {}", e.getMessage(), e);
                entity.setContent(objectMapper.createObjectNode());
            }
        } else {
            log.warn("AI返回的 content 为空，从顶层字段构建");
            ExamGenerateRequest.QuestionContent newContent = new ExamGenerateRequest.QuestionContent();
            newContent.setStem(question.getStem());
            newContent.setAnswer(question.getAnswer());
            newContent.setExplanation(question.getExplanation());
            if (question.getOptions() != null) {
                newContent.setData(java.util.Collections.singletonMap("options", question.getOptions()));
            }
            try {
                String contentJson = JSON.toJSONString(newContent);
                log.info("构建的题目内容: {}", contentJson);
                entity.setContent(objectMapper.readTree(contentJson));
            } catch (Exception e) {
                log.error("解析构建的题目内容失败: {}", e.getMessage(), e);
                entity.setContent(objectMapper.createObjectNode());
            }
        }

        ExamGenerateRequest.SourceTrace sourceTrace = question.getSourceTrace();
        log.info("=== Source Trace ===");
        log.info("sourceTrace: {}", sourceTrace);
        log.info("documentName: {}", sourceTrace != null ? sourceTrace.getDocumentName() : null);
        log.info("chunkIds: {}", sourceTrace != null ? sourceTrace.getChunkIds() : null);
        log.info("chunksCount: {}", sourceTrace != null ? sourceTrace.getChunksCount() : null);
        log.info("pageNumbers: {}", sourceTrace != null ? sourceTrace.getPageNumbers() : null);
        log.info("sources: {}", sourceTrace != null ? sourceTrace.getSources() : null);

        if (sourceTrace != null) {
            entity.setDocumentName(sourceTrace.getDocumentName());

            if (sourceTrace.getChunkIds() != null && !sourceTrace.getChunkIds().isEmpty()) {
                try {
                    entity.setChunkIds(objectMapper.readTree(JSON.toJSONString(sourceTrace.getChunkIds())));
                } catch (Exception e) {
                    log.warn("解析chunkIds失败: {}", e.getMessage());
                }
            } else if (sourceTrace.getChunksCount() != null) {
                log.warn("AI返回的 source_trace 没有 chunk_ids，只有 chunks_count: {}", sourceTrace.getChunksCount());
            }

            if (sourceTrace.getPageNumbers() != null && !sourceTrace.getPageNumbers().isEmpty()) {
                try {
                    entity.setPageNumbers(objectMapper.readTree(JSON.toJSONString(sourceTrace.getPageNumbers())));
                } catch (Exception e) {
                    log.warn("解析pageNumbers失败: {}", e.getMessage());
                }
            }

            if (sourceTrace.getSources() != null && !sourceTrace.getSources().isEmpty()) {
                StringBuilder sourceContext = new StringBuilder();
                for (ExamGenerateRequest.SourceInfo sourceInfo : sourceTrace.getSources()) {
                    if (sourceContext.length() > 0) {
                        sourceContext.append("; ");
                    }
                    if (sourceInfo.getSection() != null) {
                        sourceContext.append("Section:").append(sourceInfo.getSection());
                    }
                    if (sourceInfo.getSnippet() != null) {
                        sourceContext.append(" Snippet:").append(sourceInfo.getSnippet());
                    }
                    if (sourceInfo.getPage() != null) {
                        sourceContext.append(" Page:").append(sourceInfo.getPage());
                    }
                }
                entity.setSourceContext(sourceContext.toString());
            } else {
                log.warn("AI返回的 source_trace 没有 sources，无法生成 source_context");
                if (sourceTrace.getChunksCount() != null) {
                    entity.setSourceContext("chunks_count: " + sourceTrace.getChunksCount());
                }
            }
        }

        return entity;
    }

    private BigDecimal calculateScore(String questionType, BigDecimal aiScore, Map<String, BigDecimal> questionScores) {
        // 1. 优先使用AI返回的分数
        if (aiScore != null && aiScore.compareTo(BigDecimal.ZERO) > 0) {
            log.debug("使用AI返回的分数: questionType={}, score={}", questionType, aiScore);
            return aiScore;
        }
        
        // 2. 其次使用请求中的配置分数
        if (questionScores != null && questionScores.containsKey(questionType)) {
            BigDecimal configScore = questionScores.get(questionType);
            log.debug("使用配置的题型分数: questionType={}, score={}", questionType, configScore);
            return configScore;
        }
        
        // 3. 最后使用默认分数
        return calculateDefaultScore(questionType);
    }

    private BigDecimal calculateDefaultScore(String questionType) {
        if (questionType == null) {
            log.warn("questionType 为 null，使用默认分数 2.00");
            return new BigDecimal("2.00");
        }
        switch (questionType) {
            case "single_choice":
                return new BigDecimal("2.00");
            case "multiple_choice":
                return new BigDecimal("4.00");
            case "true_false":
                return new BigDecimal("1.00");
            case "fill_blank":
                return new BigDecimal("2.00");
            case "subjective":
                return new BigDecimal("6.00");
            default:
                log.warn("未知的 questionType: {}，使用默认分数 5.00", questionType);
                return new BigDecimal("5.00");
        }
    }
}
