<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 考试答题分析服务（步骤级分析）
 * 基于卷子分析思考文档的思路实现
 *
 * 核心流程：
 * 1. 接收卷子ID和每道题的对错、简答题的分步骤对错
 * 2. 将原子信息映射到知识点/技能
 * 3. 计算知识点掌握度向量
 * 4. 生成详细分析报告
 * 5. 提供智能出卷推荐依据
 */
class ExamAnswerAnalysisService
{
    /**
     * 缓存知识点信息，减少重复查询
     *
     * @var array<string, object|null>
     */
    private array $kpInfoCache = [];
    public function __construct(
        private readonly MasteryCalculator $masteryCalculator,
        private readonly KnowledgeMasteryService $knowledgeMasteryService,
        private readonly LocalAIAnalysisService $aiAnalysisService,
        private readonly MistakeBookService $mistakeBookService
    ) {}

    /**
     * 分析考试答题数据
     *
     * @param  array  $examData  考试数据
     * @return array 分析结果
     */
    public function analyzeExamAnswers(array $examData): array
    {
        Log::info('开始分析考试答题', [
            'paper_id' => $examData['paper_id'] ?? 'unknown',
            'student_id' => $examData['student_id'] ?? 'unknown',
            'question_count' => count($examData['questions'] ?? []),
        ]);

        $studentId = $examData['student_id'];
        $paperId = $examData['paper_id'] ?? '';
        $questions = $examData['questions'] ?? [];

        // 0. 自动计算分数并补充未提交的题目
        $questions = $this->autoCalculateScores($questions, $paperId);

        // 更新 examData 中的 questions（包含补充的题目）
        $examData['questions'] = $questions;

        // 【公司要求】1. 获取学案基准难度（取自学案的difficulty_category）
        $examBaseDifficulty = $this->getExamBaseDifficulty($examData['paper_id'] ?? '');

        // 2. 获取题目知识点映射（批量查询，避免N+1）
        $questionMappings = $this->getQuestionKnowledgeMappings($questions);

        // 3. 保存答题记录到数据库（复用已查询的知识点映射）
        $recordChangeState = $this->saveExamAnswerRecords($examData, $questionMappings);
        // 同步回写 paper_questions 判分结果，保证 PDF 与分析链路一致
        $this->syncPaperQuestionGrading($examData);

        // 同卷同答案重复提交：直接复用最近一次分析结果，避免掌握度被重复累计
        $forceRecalculate = boolval($examData['force_recalculate'] ?? false);
        if (
            !$forceRecalculate
            &&
            !($recordChangeState['steps_changed'] ?? false)
            && !($recordChangeState['questions_changed'] ?? false)
        ) {
            $existing = DB::connection('mysql')
                ->table('exam_analysis_results')
                ->where('student_id', $studentId)
                ->where('paper_id', $examData['paper_id'])
                ->orderByDesc('created_at')
                ->first();

            if ($existing && !empty($existing->analysis_data)) {
                $existingData = json_decode($existing->analysis_data, true) ?: [];
                $existingData['reused_existing_analysis'] = true;
                $existingData['reused_analysis_id'] = $existing->id;

                Log::info('同卷同答案重复提交，复用已有分析结果', [
                    'student_id' => $studentId,
                    'paper_id' => $examData['paper_id'],
                    'analysis_id' => $existing->id,
                ]);

                return $existingData;
            }
        }

        // 【公司要求】4. 计算每个知识点的加权掌握度（传入学案基准难度）
        // 核心算法：难度映射 → 权重计算 → 数值更新（newMastery = oldMastery + change）
        $knowledgeMasteryVector = $this->calculateKnowledgeMasteryVector($questions, $questionMappings, $examBaseDifficulty, $studentId);

        // 【公司要求】5. 更新学生掌握度（包含多级父节点掌握度计算）
        $updatedMastery = $this->updateStudentMastery($studentId, $knowledgeMasteryVector);

        // 5. 生成题目维度分析
        $questionAnalysis = $this->analyzeQuestions($questions, $questionMappings);

        // 6. 生成知识点维度分析
        $knowledgePointAnalysis = $this->analyzeKnowledgePoints($knowledgeMasteryVector, $questionMappings);

        // 7. 生成整体掌握度总结
        $overallSummary = $this->generateOverallSummary($updatedMastery);

        // 8. 生成智能出卷推荐依据
        $smartQuizRecommendation = $this->generateSmartQuizRecommendation($updatedMastery);

        // 9. 保存分析结果
        $analysisResult = [
            'paper_id' => $examData['paper_id'],
            'student_id' => $studentId,
            'timestamp' => now()->toISOString(),
            'question_analysis' => $questionAnalysis,
            'knowledge_point_analysis' => $knowledgePointAnalysis,
            'overall_summary' => $overallSummary,
            'smart_quiz_recommendation' => $smartQuizRecommendation,
            'mastery_vector' => $updatedMastery,
        ];

        // 【新增】创建掌握度快照，并返回 current_mastery（仅kp->mastery）
        $snapshotInfo = $this->createMasterySnapshot($studentId, $paperId, $analysisResult);
        $analysisResult['current_mastery'] = $snapshotInfo['current_mastery'] ?? [];

        $this->saveAnalysisResult($studentId, $examData['paper_id'], $analysisResult);

        Log::info('考试答题分析完成', [
            'student_id' => $studentId,
            'paper_id' => $examData['paper_id'],
            'analyzed_knowledge_points' => count($knowledgeMasteryVector),
        ]);

        return $analysisResult;
    }

    /**
     * 【公司要求】获取学案基准难度（取自学案的difficulty_category）
     *
     * 公司要求：
     * 入参需要增加 {学案基准难度}（取自学案的 difficulty_category）
     *
     * @param  string  $paperId  试卷ID
     * @return int|null 学案基准难度（1-4级），失败返回null
     */
    private function getExamBaseDifficulty(string $paperId): ?int
    {
        if (empty($paperId)) {
            return null;
        }
        try {
            // 【公司要求】入参需要增加 {学案基准难度}（取自学案的 difficulty_category）
            // 从试卷表获取difficulty_category
            $paper = DB::table('papers')
                ->where('paper_id', $paperId)
                ->first();

            if (! $paper) {
                Log::warning('未找到试卷，尝试从缓存获取', ['paper_id' => $paperId]);

                return 2;
            }

            return $paper->difficulty_category ?? 2;
        } catch (\Exception $e) {
            Log::warning('获取学案基准难度失败，使用默认2级', [
                'paper_id' => $paperId,
                'error' => $e->getMessage(),
            ]);

            return 2; // 默认中等难度
        }
    }

    /**
     * 获取题目知识点映射
     * 【优化】优先使用批量查询，失败时降级到单条查询
     */
    private function getQuestionKnowledgeMappings(array $questions): array
    {
        $mappings = [];
        $failedQuestions = [];

        // 收集所有题目ID
        $questionIds = [];
        foreach ($questions as $question) {
            $questionId = $question['question_id'] ?? null;
            if ($questionId) {
                $questionIds[] = $questionId;
            }
        }

        // 【优化】尝试批量查询
        $batchResult = [];
        if (! empty($questionIds)) {
            $batchResult = $this->batchGetQuestionKnowledgePoints($questionIds);
        }

        // 【优化】对批量未命中的题目再做一次批量补偿，减少单条查询
        $missingQuestionIds = [];
        if (! empty($questionIds)) {
            foreach ($questionIds as $qid) {
                if (! isset($batchResult[$qid])) {
                    $missingQuestionIds[] = $qid;
                }
            }
        }
        $fallbackBatchResult = [];
        if (! empty($missingQuestionIds)) {
            $fallbackBatchResult = $this->batchGetQuestionKnowledgePoints($missingQuestionIds);
        }

        // 遍历题目，优先使用批量结果，否则降级到单条查询
        foreach ($questions as $question) {
            $questionId = $question['question_id'] ?? null;
            if (! $questionId) {
                continue;
            }

            $kpMapping = [];

            // 优先使用批量查询结果
            if (isset($batchResult[$questionId])) {
                $kpMapping = $batchResult[$questionId];
                Log::debug('使用批量查询结果', [
                    'question_id' => $questionId,
                    'kp_count' => count($kpMapping),
                ]);
            } elseif (isset($fallbackBatchResult[$questionId])) {
                $kpMapping = $fallbackBatchResult[$questionId];
                Log::debug('使用补偿批量查询结果', [
                    'question_id' => $questionId,
                    'kp_count' => count($kpMapping),
                ]);
            } else {
                // 降级：使用单条查询（批量查询可能遗漏的题目）
                $dbKpMappings = $this->getQuestionKnowledgePointsFromDb($questionId);
                if (! empty($dbKpMappings)) {
                    $kpMapping = $dbKpMappings;
                    Log::debug('降级到单条查询', [
                        'question_id' => $questionId,
                        'kp_count' => count($dbKpMappings),
                    ]);
                }
            }

            // 如果仍然没有知识点信息，跳过该题目
            if (empty($kpMapping)) {
                $failedQuestions[] = $questionId;
                Log::warning('跳过无法获取知识点的题目', [
                    'question_id' => $questionId,
                ]);

                continue;
            }

            $mappings[$questionId] = [
                'question_id' => $questionId,
                'kp_mapping' => $kpMapping,
            ];
        }

        if (! empty($failedQuestions)) {
            Log::warning('部分题目无法获取知识点信息', [
                'failed_questions' => $failedQuestions,
                'total_questions' => count($questions),
                'mapped_questions' => count($mappings),
            ]);
        }

        Log::info('题目知识点映射构建完成', [
            'total_questions' => count($questions),
            'mapped_questions' => count($mappings),
            'failed_questions' => count($failedQuestions),
            'batch_hit_count' => count($batchResult),
        ]);

        return $mappings;
    }

    /**
     * 从数据库获取题目的知识点信息（支持多知识点）
     * 如果题目没有直接的知识点，通过目录ID匹配知识点
     */
    private function getQuestionKnowledgePointsFromDb(string $questionId): array
    {
        $allKpMappings = [];

        try {
            // 【第一步】从 questions 表直接获取知识点字段（可能有多个）
            $question = DB::connection('mysql')
                ->table('questions')
                ->where('id', $questionId)
                ->orWhere('question_code', $questionId)
                ->first();

            if ($question) {
                // 检查题目的直接知识点字段
                $directKpCodes = [];
                $kpCode1 = $question->kp_code;
                if ($kpCode1) {
                    $directKpCodes[] = $kpCode1;
                }

                // 获取每个知识点的详细信息
                foreach ($directKpCodes as $kpCode) {
                    $kpInfo = $this->getKnowledgePointInfo($kpCode);

                    if ($kpInfo) {
                        $allKpMappings[] = [
                            'kp_id' => $kpCode,
                            'kp_name' => $kpInfo->name,
                            'weight' => 1.0,
                        ];
                    } else {
                        // 如果knowledge_points表中没有记录，仍然添加
                        $allKpMappings[] = [
                            'kp_id' => $kpCode,
                            'kp_name' => $kpCode,
                            'weight' => 1.0,
                        ];
                    }
                }

                if (! empty($directKpCodes)) {
                    Log::debug('从题目直接字段获取知识点', [
                        'question_id' => $questionId,
                        'kp_codes' => $directKpCodes,
                        'mapped_count' => count($allKpMappings),
                    ]);
                }
            }

            // 【第二步】如果题目没有直接的知识点，通过目录ID匹配知识点
            if (empty($allKpMappings) && $question) {
                $catalogKpMappings = $this->findKpCodesByCatalog($question);
                if (! empty($catalogKpMappings)) {
                    $allKpMappings = $catalogKpMappings;
                    Log::debug('通过目录ID匹配到知识点', [
                        'question_id' => $questionId,
                        'matched_kp_codes' => array_column($catalogKpMappings, 'kp_id'),
                        'matched_count' => count($catalogKpMappings),
                    ]);
                }
            }

            if (empty($allKpMappings)) {
                Log::warning('未找到题目的知识点信息', [
                    'question_id' => $questionId,
                ]);
            }

        } catch (\Exception $e) {
            Log::error('获取题目知识点信息失败', [
                'question_id' => $questionId,
                'error' => $e->getMessage(),
            ]);
        }

        return $allKpMappings;
    }

    /**
     * 通过题目的目录信息匹配知识点
     * 使用 textbook_catalog_nodes_id -> textbook_chapter_knowledge_relation 表查询
     */
    private function findKpCodesByCatalog(object $question): array
    {
        $kpMappings = [];

        try {
            // 获取题目的教材目录节点ID
            $catalogNodesId = $question->textbook_catalog_nodes_id;

            if (! $catalogNodesId) {
                Log::debug('题目没有关联的教材目录节点', [
                    'question_id' => $question->id,
                ]);

                return $kpMappings;
            }

            // 通过 catalog_chapter_id 查询关联的知识点
            $relations = DB::connection('mysql')
                ->table('textbook_chapter_knowledge_relation')
                ->where('catalog_chapter_id', $catalogNodesId)
                ->where('is_deleted', 0) // 只查询未删除的关联
                ->get();

            if ($relations->isNotEmpty()) {
                foreach ($relations as $relation) {
                    $kpCode = $relation->kp_code;
                    $kpInfo = $this->getKnowledgePointInfo($kpCode);

                    $kpMappings[] = [
                        'kp_id' => $kpCode,
                        'kp_name' => $kpInfo->name ?? $kpCode,
                        'weight' => 1.0,
                    ];
                }

                Log::debug('通过教材目录节点匹配到知识点', [
                    'question_id' => $question->id,
                    'catalog_nodes_id' => $catalogNodesId,
                    'matched_kp_count' => count($kpMappings),
                    'matched_kp_codes' => array_column($kpMappings, 'kp_id'),
                ]);
            } else {
                Log::debug('教材目录节点没有关联的知识点', [
                    'question_id' => $question->id,
                    'catalog_nodes_id' => $catalogNodesId,
                ]);
            }

        } catch (\Exception $e) {
            Log::error('通过目录匹配知识点失败', [
                'question_id' => $question->id,
                'error' => $e->getMessage(),
            ]);
        }

        return $kpMappings;
    }

    /**
     * 保留原有方法用于向后兼容，但标记为废弃
     */
    private function getQuestionKnowledgePointFromDb(string $questionId): ?array
    {
        $kpMappings = $this->getQuestionKnowledgePointsFromDb($questionId);

        return ! empty($kpMappings) ? $kpMappings[0] : null;
    }

    /**
     * 获取知识点信息（带进程内缓存）
     */
    private function getKnowledgePointInfo(string $kpCode): ?object
    {
        if (isset($this->kpInfoCache[$kpCode])) {
            return $this->kpInfoCache[$kpCode];
        }

        $kpInfo = DB::connection('mysql')
            ->table('knowledge_points')
            ->where('kp_code', $kpCode)
            ->select(['kp_code', 'name'])
            ->first();

        $this->kpInfoCache[$kpCode] = $kpInfo ?: null;

        return $kpInfo;
    }

    /**
     * 【优化】批量获取题目的知识点信息
     * 将 N+1 查询优化为 2-3 次批量查询
     *
     * @param  array  $questionIds  题目ID数组
     * @return array [questionId => [kpMappings...]] 映射
     */
    private function batchGetQuestionKnowledgePoints(array $questionIds): array
    {
        if (empty($questionIds)) {
            return [];
        }

        $result = [];
        $questionsNeedCatalogLookup = []; // 需要通过目录查找知识点的题目

        try {
            // 【第1步】批量查询 questions 表（1次查询）
            $questionsData = DB::connection('mysql')
                ->table('questions')
                ->whereIn('id', $questionIds)
                ->orWhereIn('question_code', $questionIds)
                ->get();

            // 建立 ID 到题目数据的映射
            $questionMap = [];
            foreach ($questionsData as $q) {
                $questionMap[$q->id] = $q;
                if ($q->question_code) {
                    $questionMap[$q->question_code] = $q;
                }
            }

            // 【第2步】收集所有直接关联的 kp_code
            $allKpCodes = [];
            foreach ($questionsData as $q) {
                if (! empty($q->kp_code)) {
                    $allKpCodes[] = $q->kp_code;
                }
            }

            // 【第3步】批量查询 knowledge_points 表（1次查询）
            $kpInfoMap = [];
            if (! empty($allKpCodes)) {
                $kpInfos = DB::connection('mysql')
                    ->table('knowledge_points')
                    ->whereIn('kp_code', array_unique($allKpCodes))
                    ->get();

                foreach ($kpInfos as $kp) {
                    $kpInfoMap[$kp->kp_code] = $kp;
                }
            }

            // 【第4步】收集需要通过目录查找的题目
            $catalogNodeIds = [];
            foreach ($questionsData as $q) {
                if (empty($q->kp_code) && ! empty($q->textbook_catalog_nodes_id)) {
                    $catalogNodeIds[] = $q->textbook_catalog_nodes_id;
                    $questionsNeedCatalogLookup[$q->id] = $q;
                }
            }

            // 【第5步】批量查询目录-知识点关系（1次查询）
            $catalogKpMap = [];
            if (! empty($catalogNodeIds)) {
                $catalogRelations = DB::connection('mysql')
                    ->table('textbook_chapter_knowledge_relation')
                    ->whereIn('catalog_chapter_id', array_unique($catalogNodeIds))
                    ->where('is_deleted', 0)
                    ->get();

                // 收集目录关联的 kp_code
                $catalogKpCodes = [];
                foreach ($catalogRelations as $rel) {
                    $catalogKpCodes[] = $rel->kp_code;
                    if (! isset($catalogKpMap[$rel->catalog_chapter_id])) {
                        $catalogKpMap[$rel->catalog_chapter_id] = [];
                    }
                    $catalogKpMap[$rel->catalog_chapter_id][] = $rel->kp_code;
                }

                // 批量查询这些知识点的信息
                if (! empty($catalogKpCodes)) {
                    $catalogKpInfos = DB::connection('mysql')
                        ->table('knowledge_points')
                        ->whereIn('kp_code', array_unique($catalogKpCodes))
                        ->get();

                    foreach ($catalogKpInfos as $kp) {
                        $kpInfoMap[$kp->kp_code] = $kp;
                    }
                }
            }

            // 【第6步】组装结果
            foreach ($questionIds as $questionId) {
                $qData = $questionMap[$questionId] ?? null;
                if (! $qData) {
                    Log::debug('批量查询未找到题目', ['question_id' => $questionId]);

                    continue;
                }

                $kpMappings = [];

                // 方式1：直接从 kp_code 字段获取
                if (! empty($qData->kp_code)) {
                    $kpCode = $qData->kp_code;
                    $kpInfo = $kpInfoMap[$kpCode] ?? null;
                    $kpMappings[] = [
                        'kp_id' => $kpCode,
                        'kp_name' => $kpInfo->name ?? $kpCode,
                        'weight' => 1.0,
                    ];
                }
                // 方式2：通过目录关系获取
                elseif (! empty($qData->textbook_catalog_nodes_id)) {
                    $catalogId = $qData->textbook_catalog_nodes_id;
                    $catalogKpCodes = $catalogKpMap[$catalogId] ?? [];
                    foreach ($catalogKpCodes as $kpCode) {
                        $kpInfo = $kpInfoMap[$kpCode] ?? null;
                        $kpMappings[] = [
                            'kp_id' => $kpCode,
                            'kp_name' => $kpInfo->name ?? $kpCode,
                            'weight' => 1.0,
                        ];
                    }
                }

                if (! empty($kpMappings)) {
                    $result[$questionId] = $kpMappings;
                }
            }

            Log::info('批量获取题目知识点完成', [
                'input_count' => count($questionIds),
                'output_count' => count($result),
                'query_count' => '2-4次（优化后）',
            ]);

        } catch (\Exception $e) {
            Log::error('批量获取题目知识点失败，将降级到单条查询', [
                'question_ids' => $questionIds,
                'error' => $e->getMessage(),
            ]);

            // 降级：返回空，让调用方使用单条查询
            return [];
        }

        return $result;
    }

    /**
     * 从 QuestionBank API 获取题目信息
     */
    private function getQuestionFromQuestionBank(string $questionId): ?array
    {
        try {
            $baseUrl = config('services.question_bank_api.base_url', 'http://question-bank-api:5015');
            $response = Http::timeout(10)->get($baseUrl.'/questions/'.$questionId);

            if ($response->successful()) {
                $data = $response->json();

                return $data['data'] ?? null;
            }

            return null;
        } catch (\Exception $e) {
            Log::warning('从QuestionBank获取题目信息失败', [
                'question_id' => $questionId,
                'error' => $e->getMessage(),
            ]);

            return null;
        }
    }

    /**
     * 批量获取题目难度
     *
     * @param  array  $questionIds  题目ID数组
     * @return array [questionId => difficulty] 映射
     */
    private function batchGetQuestionDifficulties(array $questionIds): array
    {
        if (empty($questionIds)) {
            return [];
        }

        $difficulties = [];

        try {
            $questions = DB::connection('mysql')
                ->table('questions')
                ->whereIn('id', $questionIds)
                ->orWhereIn('question_code', $questionIds)
                ->select(['id', 'question_code', 'difficulty'])
                ->get();

            foreach ($questions as $question) {
                $difficulty = $question->difficulty !== null ? floatval($question->difficulty) : 0.6;
                // 同时用 id 和 question_code 作为键，确保能匹配到
                $difficulties[$question->id] = $difficulty;
                if ($question->question_code) {
                    $difficulties[$question->question_code] = $difficulty;
                }
            }
        } catch (\Exception $e) {
            Log::warning('批量获取题目难度失败', [
                'question_ids' => $questionIds,
                'error' => $e->getMessage(),
            ]);
        }

        return $difficulties;
    }

    /**
     * 【公司要求】计算知识点掌握度向量
     *
     * 公司要求的核心算法：
     * 1. 难度映射：将题目中0.0-1.0的浮点数难度映射为 1-4 等级
     * 2. 权重计算：
     *    - 越级（Question > {学案基准难度}）：对 +0.15 / 错 -0.05
     *    - 适应（Question = {学案基准难度}）：对 +0.10 / 错 -0.10
     *    - 降级（Question < {学案基准难度}）：对 +0.05 / 错 -0.15
     * 3. 数值更新：newMastery = oldMastery + change，并做 0.0 ~ 1.0 的边界限制
     *
     * 核心算法说明：
     * 1. 从考试答题中提取每个知识点的答题记录
     * 2. 调用MasteryCalculator计算掌握度（包含：难度映射、权重计算、数值更新）
     * 3. 返回包含掌握度、置信度、趋势等完整信息的向量
     *
     * @param  array  $questions  题目列表
     * @param  array  $questionMappings  题目知识点映射
     * @param  int|null  $examBaseDifficulty  学案基准难度（1-4级）
     * @param  string|null  $studentId  学生ID
     * @return array 知识点掌握度向量
     */
    private function calculateKnowledgeMasteryVector(array $questions, array $questionMappings, ?int $examBaseDifficulty = null, ?string $studentId = null): array
    {
        // 按知识点聚合答题记录
        $knowledgeAttempts = [];

        // 批量获取所有题目的难度（减少数据库查询次数）
        $questionIds = array_filter(array_map(fn ($q) => $q['question_id'] ?? $q['question_bank_id'] ?? null, $questions));
        $questionDifficulties = $this->batchGetQuestionDifficulties($questionIds);

        foreach ($questions as $question) {
            $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
            if (empty($questionId)) {
                Log::warning('calculateKnowledgeMasteryVector: 题目缺少ID', ['question' => $question]);

                continue;
            }

            $score = floatval($question['score_obtained'] ?? 0);
            $maxScore = floatval($question['score'] ?? $score);

            // is_correct 是数组，如 [0,1,1]，表示每个步骤的正误
            $isCorrectArray = $question['is_correct'] ?? [];
            if (! is_array($isCorrectArray)) {
                $isCorrectArray = [$isCorrectArray ? 1 : 0];
            }

            $mapping = $questionMappings[$questionId] ?? null;
            if (! $mapping || ! isset($mapping['kp_mapping'])) {
                Log::debug('calculateKnowledgeMasteryVector: 题目无知识点映射', ['question_id' => $questionId]);

                continue;
            }

            // 从批量查询结果获取题目难度
            $questionDifficulty = $questionDifficulties[$questionId] ?? 0.6;

            $stepCount = count($isCorrectArray);
            $scorePerStep = $maxScore / max($stepCount, 1);

            // 根据 is_correct 数组生成步骤级答题记录
            foreach ($isCorrectArray as $stepIndex => $isCorrect) {
                $isCorrectBool = (int) $isCorrect === 1;

                // 为该题目关联的每个知识点创建答题记录
                foreach ($mapping['kp_mapping'] as $kpMapping) {
                    $kpId = $kpMapping['kp_id'];

                    if (! isset($knowledgeAttempts[$kpId])) {
                        $knowledgeAttempts[$kpId] = [
                            'attempts' => [],
                            'step_details' => [],
                        ];
                    }

                    // 构建答题记录（用于MasteryCalculator）
                    $attemptRecord = [
                        'question_id' => $questionId,
                        'is_correct' => $isCorrectBool,
                        'step_index' => $stepIndex,
                        'question_difficulty' => $questionDifficulty,
                        'created_at' => now()->toISOString(),
                    ];

                    $knowledgeAttempts[$kpId]['attempts'][] = $attemptRecord;
                    $knowledgeAttempts[$kpId]['step_details'][] = [
                        'question_id' => $questionId,
                        'step_index' => $stepIndex,
                        'score' => $isCorrectBool ? $scorePerStep : 0,
                        'max_score' => $scorePerStep,
                        'is_correct' => $isCorrectBool,
                    ];
                }
            }
        }

        // 【公司要求】【核心】使用MasteryCalculator计算每个知识点的掌握度
        // 性能优化：批量读取历史 + 批量upsert，避免逐知识点查询与写入
        $baseDifficulty = $examBaseDifficulty ?? 2;
        $batchMasteryResults = $this->masteryCalculator->calculateMasteryLevelsBatch(
            $studentId ?? '',
            $knowledgeAttempts,
            $baseDifficulty
        );
        $masteryVector = [];
        foreach ($knowledgeAttempts as $kpId => $data) {
            $masteryResult = $batchMasteryResults[$kpId] ?? null;
            if ($masteryResult === null) {
                continue;
            }
            $masteryVector[$kpId] = [
                'kp_id' => $kpId,
                'mastery' => $masteryResult['mastery'],
                'previous_mastery' => $masteryResult['old_mastery'] ?? null,
                'change' => $masteryResult['change'] ?? null,
                'total_attempts' => $masteryResult['total_attempts'],
                'correct_attempts' => $masteryResult['correct_attempts'],
                'accuracy_rate' => $masteryResult['accuracy_rate'],
                'step_details' => $data['step_details'],
                // 计算细节（用于调试和分析）
                'calculation_details' => $masteryResult['details'] ?? [],
            ];
        }

        Log::info('知识点掌握度向量计算完成', [
            'knowledge_points_count' => count($masteryVector),
            'sample' => array_slice($masteryVector, 0, 3, true),
        ]);

        return $masteryVector;
    }

    /**
     * 更新学生掌握度（优化版：批量查询+批量upsert）
     */
    private function updateStudentMastery(string $studentId, array $knowledgeMasteryVector): array
    {
        if (empty($knowledgeMasteryVector)) {
            return [];
        }

        $updatedMastery = [];
        $kpIds = array_keys($knowledgeMasteryVector);
        // 子节点掌握度已在 MasteryCalculator 内部写库，这里只生成返回数据，避免二次写入与重复统计
        foreach ($knowledgeMasteryVector as $kpId => $data) {
            $previousMastery = $data['previous_mastery'] ?? 0.0;

            $updatedMastery[$kpId] = [
                'kp_id' => $kpId,
                'current_mastery' => $data['mastery'],
                'previous_mastery' => $previousMastery,
                'change' => $data['mastery'] - $previousMastery,
                'weight' => 1,
                'is_parent' => false,
            ];
        }

        // 【修复】计算并更新父节点掌握度，同时添加到返回数组中
        $parentMasteryData = $this->updateParentMasteryLevels($studentId, $kpIds);

        // 合并父节点数据到返回数组
        $updatedMastery = array_merge($updatedMastery, $parentMasteryData);

        return $updatedMastery;
    }

    /**
     * 更新父节点掌握度（优化版：批量查询+批量upsert）
     * 父节点掌握度 = 所有子节点掌握度的算术平均数，支持多级递归
     */
    private function updateParentMasteryLevels(string $studentId, array $childKpCodes, int $maxDepth = 2): array
    {
        $allParentMasteryData = [];
        $currentLevelChildCodes = $childKpCodes;
        $processedNodes = new \ArrayObject;
        $now = now();

        try {
            for ($level = 0; $level < $maxDepth; $level++) {
                if (empty($currentLevelChildCodes)) {
                    break;
                }

                // 获取当前层子节点的直接父节点
                $parentKpCodes = DB::connection('mysql')
                    ->table('knowledge_points')
                    ->whereIn('kp_code', $currentLevelChildCodes)
                    ->whereNotNull('parent_kp_code')
                    ->distinct()
                    ->pluck('parent_kp_code')
                    ->toArray();

                if (empty($parentKpCodes)) {
                    break;
                }

                // 过滤已处理的节点
                $parentKpCodesToProcess = [];
                foreach ($parentKpCodes as $code) {
                    if (! isset($processedNodes[$code])) {
                        $processedNodes[$code] = true;
                        $parentKpCodesToProcess[] = $code;
                    }
                }

                if (empty($parentKpCodesToProcess)) {
                    $currentLevelChildCodes = $parentKpCodes;

                    continue;
                }

                // 批量获取父节点的直接子节点
                $childRelations = DB::connection('mysql')
                    ->table('knowledge_points')
                    ->whereIn('parent_kp_code', $parentKpCodesToProcess)
                    ->get(['kp_code', 'parent_kp_code']);

                $childrenByParent = [];
                $allChildCodes = [];
                foreach ($childRelations as $relation) {
                    $childrenByParent[$relation->parent_kp_code][] = $relation->kp_code;
                    $allChildCodes[$relation->kp_code] = true;
                }

                // 批量获取子节点掌握度
                $childMasteryMap = [];
                if (! empty($allChildCodes)) {
                    $childMasteryMap = DB::connection('mysql')
                        ->table('student_knowledge_mastery')
                        ->where('student_id', $studentId)
                        ->whereIn('kp_code', array_keys($allChildCodes))
                        ->pluck('mastery_level', 'kp_code')
                        ->toArray();
                }

                // 批量查询父节点历史掌握度
                $historyRecords = DB::connection('mysql')
                    ->table('student_knowledge_mastery')
                    ->where('student_id', $studentId)
                    ->whereIn('kp_code', $parentKpCodesToProcess)
                    ->get()
                    ->keyBy('kp_code');

                // 计算每个父节点的掌握度并收集upsert数据
                $upsertData = [];
                $currentLevelParentData = [];

                foreach ($parentKpCodesToProcess as $parentKpCode) {
                    $children = $childrenByParent[$parentKpCode] ?? [];
                    $sum = 0.0;
                    $count = 0;
                    foreach ($children as $childCode) {
                        if (isset($childMasteryMap[$childCode])) {
                            $sum += (float) $childMasteryMap[$childCode];
                            $count++;
                        }
                    }
                    $parentMastery = $count > 0 ? round($sum / $count, 4) : 0.0;

                    $historyMastery = $historyRecords->get($parentKpCode);
                    $previousMastery = $historyMastery->mastery_level ?? 0.0;

                    $upsertData[] = [
                        'student_id' => $studentId,
                        'kp_code' => $parentKpCode,
                        'mastery_level' => $parentMastery,
                        'confidence_level' => 0.0,
                        'total_attempts' => 1,
                        'correct_attempts' => 0,
                        'mastery_trend' => 'stable',
                        'last_mastery_update' => $now,
                        'updated_at' => $now,
                    ];

                    $currentLevelParentData[$parentKpCode] = [
                        'kp_id' => $parentKpCode,
                        'current_mastery' => $parentMastery,
                        'previous_mastery' => $previousMastery,
                        'change' => $parentMastery - $previousMastery,
                        'weight' => 1,
                        'is_parent' => true,
                        'level' => $level + 1,
                    ];
                }

                // 【优化】批量upsert（1次查询代替N次updateOrInsert）
                if (! empty($upsertData)) {
                    DB::connection('mysql')
                        ->table('student_knowledge_mastery')
                        ->upsert(
                            $upsertData,
                            ['student_id', 'kp_code'],
                            ['mastery_level', 'confidence_level', 'total_attempts', 'correct_attempts', 'mastery_trend', 'last_mastery_update', 'updated_at']
                        );
                }

                $allParentMasteryData = array_merge($allParentMasteryData, $currentLevelParentData);
                $currentLevelChildCodes = $parentKpCodes;
            }

            if (! empty($allParentMasteryData)) {
                Log::info('多级父节点掌握度计算完成', [
                    'student_id' => $studentId,
                    'child_count' => count($childKpCodes),
                    'total_parent_count' => count($allParentMasteryData),
                ]);
            }

        } catch (\Exception $e) {
            Log::error('计算多级父节点掌握度失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage(),
            ]);
        }

        return $allParentMasteryData;
    }

    /**
     * 生成题目维度分析（包含AI分析和解题思路）
     */
    private function analyzeQuestions(array $questions, array $questionMappings): array
    {
        $analysis = [];

        foreach ($questions as $question) {
            $questionId = $question['question_id'];
            $score = floatval($question['score_obtained'] ?? 0);
            $maxScore = floatval($question['score'] ?? $score);
            $steps = $question['steps'] ?? [];
            $isCorrect = $question['is_correct'] ?? ($score >= $maxScore);

            $mapping = $questionMappings[$questionId] ?? ['kp_mapping' => []];
            if (empty($mapping['kp_mapping'])) {
                Log::warning('ExamAnswerAnalysisService: 题目无知识点映射', ['question_id' => $questionId]);

                continue;
            }
            $kpCode = $mapping['kp_mapping'][0]['kp_id'];

            // 步骤分析
            $stepAnalysis = [];
            if (! empty($steps)) {
                foreach ($steps as $step) {
                    $kpId = $step['kp_id'];
                    if (empty($kpId)) {
                        Log::warning('ExamAnswerAnalysisService: 步骤缺少知识点ID', [
                            'question_id' => $questionId,
                            'step_index' => $step['step_index'] ?? 'unknown',
                        ]);

                        continue;
                    }
                    $stepAnalysis[] = [
                        'step_index' => $step['step_index'],
                        'is_correct' => $step['is_correct'],
                        'kp_id' => $kpId,
                        'description' => $step['description'] ?? '',
                    ];
                }
            }

            // 知识点关联
            $knowledgePoints = array_map(function ($kp) {
                return [
                    'kp_id' => $kp['kp_id'],
                    'kp_name' => $kp['kp_name'] ?? $kp['kp_id'],
                    'weight' => $kp['weight'] ?? 1.0,
                ];
            }, $mapping['kp_mapping']);

            // 【集成】调用AI分析服务，获取解题思路和错误分析
            $aiAnalysis = $this->getQuestionAIAnalysis($question, $mapping);

            $analysis[] = [
                'question_id' => $questionId,
                'score_obtained' => $score,
                'max_score' => $maxScore,
                'accuracy_rate' => $maxScore > 0 ? $score / $maxScore : 0,
                'is_correct' => $isCorrect,
                'step_analysis' => $stepAnalysis,
                'knowledge_points' => $knowledgePoints,
                'performance_summary' => $this->generateQuestionPerformanceSummary($question, $stepAnalysis),
                // 【新增】解题思路和错误分析
                'solution_process' => $aiAnalysis['solution_process'] ?? '',
                'error_analysis' => $aiAnalysis['error_analysis'] ?? '',
                'mistake_type' => $aiAnalysis['mistake_type'] ?? '',
                'suggestions' => $aiAnalysis['suggestions'] ?? '',
                'next_steps' => $aiAnalysis['next_steps'] ?? [],
            ];
        }

        return $analysis;
    }

    /**
     * 获取题目的AI分析（解题思路、错误分析）
     */
    private function getQuestionAIAnalysis(array $question, array $mapping): array
    {
        $isCorrect = $question['is_correct'] ?? false;
        $score = floatval($question['score_obtained'] ?? 0);
        $maxScore = floatval($question['score'] ?? 10);
        $kpCode = $mapping['kp_mapping'][0]['kp_id'] ?? null;
        if (empty($kpCode)) {
            Log::warning('ExamAnswerAnalysisService: getQuestionAIAnalysis缺少知识点ID', [
                'question_id' => $question['question_id'] ?? 'unknown',
                'mapping' => $mapping,
            ]);
            $kpCode = 'UNKNOWN_KP';
        }

        // 调用LocalAIAnalysisService进行分析
        try {
            $analysisResult = $this->aiAnalysisService->analyzeAnswer([
                'question_id' => $question['question_id'],
                'question_text' => $question['question_text'] ?? '',
                'student_answer' => $question['student_answer'] ?? '',
                'correct_answer' => $question['correct_answer'] ?? '',
                'score' => $score,
                'max_score' => $maxScore,
                'kp_code' => $kpCode,
            ]);

            $data = $analysisResult['data'] ?? [];

            // 根据正确性生成不同的解题思路
            if ($isCorrect) {
                return [
                    'solution_process' => $data['correct_solution'] ?? '该题作答正确，解题思路清晰',
                    'error_analysis' => '',
                    'mistake_type' => '',
                    'suggestions' => $data['suggestions'] ?? '继续保持良好的解题习惯',
                    'next_steps' => $data['next_steps'] ?? ['尝试更高难度的同类题目'],
                ];
            }

            // 错误题目：返回详细分析
            return [
                'solution_process' => $data['correct_solution'] ?? '请参考标准解题步骤',
                'error_analysis' => $data['reason'] ?? '解题过程中存在错误',
                'mistake_type' => $data['mistake_type'] ?? '计算或理解错误',
                'suggestions' => $data['suggestions'] ?? '建议针对薄弱知识点进行专项练习',
                'next_steps' => $data['next_steps'] ?? ['复习相关知识点', '做同类型练习题'],
            ];

        } catch (\Exception $e) {
            Log::warning('AI分析失败，使用默认分析', [
                'question_id' => $question['question_id'],
                'error' => $e->getMessage(),
            ]);

            // 回退到基础分析
            return $this->getFallbackAnalysis($question, $isCorrect);
        }
    }

    /**
     * 回退分析（当AI分析失败时）
     */
    private function getFallbackAnalysis(array $question, bool $isCorrect): array
    {
        if ($isCorrect) {
            return [
                'solution_process' => '该题作答正确',
                'error_analysis' => '',
                'mistake_type' => '',
                'suggestions' => '继续保持',
                'next_steps' => ['尝试更高难度的题目'],
            ];
        }

        $scoreRatio = floatval($question['score_obtained'] ?? 0) / max(floatval($question['score'] ?? 1), 1);

        return [
            'solution_process' => '请参考标准答案和解题步骤',
            'error_analysis' => $scoreRatio < 0.3 ? '知识点理解存在偏差' : '解题过程中出现错误',
            'mistake_type' => $scoreRatio < 0.3 ? '概念错误' : '计算/步骤错误',
            'suggestions' => '建议复习相关知识点，加强练习',
            'next_steps' => ['复习基础概念', '做同类型练习题', '请教老师或同学'],
        ];
    }

    /**
     * 生成知识点维度分析
     */
    private function analyzeKnowledgePoints(array $knowledgeMasteryVector, array $questionMappings): array
    {
        $analysis = [];

        foreach ($knowledgeMasteryVector as $kpId => $data) {
            $totalAttempts = intval($data['total_attempts'] ?? 0);
            $correctAttempts = intval($data['correct_attempts'] ?? 0);
            $examAccuracyRatio = $totalAttempts > 0 ? ($correctAttempts / $totalAttempts) : null;
            $historicalMastery = floatval($data['mastery'] ?? 0);

            // 收敛规则（最小影响）：
            // 仅调整“报告展示口径”，不改 student_knowledge_mastery 的历史累计值。
            // 当次有错题时，采用“历史掌握度 + 当次正确率”的证据加权融合：
            //   display = (historical*PRIOR_WEIGHT + examAccuracy*evidenceWeight) / (PRIOR_WEIGHT + evidenceWeight)
            // 这样避免一次异常把 100% 直接打到 0%，同时保证有错会下调。
            $displayMastery = $historicalMastery;
            if ($examAccuracyRatio !== null && $correctAttempts < $totalAttempts) {
                $priorWeight = 8.0; // 历史先验权重（固定，保证历史连续性）
                $evidenceWeight = max(1.0, min(10.0, floatval($totalAttempts))); // 当次证据权重（随作答量提升）
                $displayMastery = (
                    ($historicalMastery * $priorWeight) + ($examAccuracyRatio * $evidenceWeight)
                ) / ($priorWeight + $evidenceWeight);
            }

            $displayData = $data;
            $displayData['mastery'] = round($displayMastery, 4);

            // 【公司要求】移除置信度，只保留核心掌握度分析
            $analysis[] = [
                'kp_id' => $kpId,
                'mastery_level' => round($displayMastery, 4),
                'historical_mastery_level' => round($historicalMastery, 4),
                'exam_accuracy_rate' => $examAccuracyRatio !== null ? round($examAccuracyRatio, 4) : null,
                'performance_in_exam' => $this->evaluatePerformanceLevel($displayMastery),
                'evidence_count' => count($data['step_details']),
                'step_evidence' => $data['step_details'],
                'recommendation' => $this->generateKnowledgePointRecommendation($displayData),
            ];
        }

        return $analysis;
    }

    /**
     * 生成整体掌握度总结
     */
    private function generateOverallSummary(array $updatedMastery): array
    {
        $knowledgePoints = array_values($updatedMastery);

        if (empty($knowledgePoints)) {
            return [
                'total_knowledge_points' => 0,
                'average_mastery' => 0,
                'mastery_distribution' => [
                    'mastered' => 0,
                    'good' => 0,
                    'weak' => 0,
                ],
                'top_strengths' => [],
                'top_weaknesses' => [],
            ];
        }

        // 计算平均掌握度（只计算子节点，不包括父节点）
        $childNodes = array_filter($knowledgePoints, fn ($kp) => ! ($kp['is_parent'] ?? false));
        $totalChildNodes = count($childNodes);

        if ($totalChildNodes === 0) {
            // 如果没有子节点，只计算所有节点
            $averageMastery = array_sum(array_column($knowledgePoints, 'current_mastery')) / count($knowledgePoints);
        } else {
            // 计算所有节点的平均掌握度（包括父节点）
            $allMastery = array_column($knowledgePoints, 'current_mastery');
            $averageMastery = array_sum($allMastery) / count($allMastery);
        }

        // 掌握度分布（只统计子节点）
        $mastered = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] >= 0.85);
        $good = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] >= 0.70 && $kp['current_mastery'] < 0.85);
        $weak = array_filter($childNodes, fn ($kp) => $kp['current_mastery'] < 0.70);

        // 排序找出优势和薄弱点（只包括子节点）
        usort($childNodes, fn ($a, $b) => $b['current_mastery'] <=> $a['current_mastery']);
        $topStrengths = array_slice($childNodes, 0, 3);
        $topWeaknesses = array_slice(array_reverse($childNodes), 0, 3);

        // 统计父子节点数量
        $childCount = count(array_filter($knowledgePoints, fn ($kp) => ! ($kp['is_parent'] ?? false)));
        $parentCount = count(array_filter($knowledgePoints, fn ($kp) => $kp['is_parent'] ?? false));

        return [
            'total_knowledge_points' => $totalChildNodes, // 只统计子节点数量
            'child_nodes_count' => $childCount,
            'parent_nodes_count' => $parentCount,
            'average_mastery' => round($averageMastery, 4),
            'mastery_distribution' => [
                'mastered' => count($mastered),
                'good' => count($good),
                'weak' => count($weak),
            ],
            'top_strengths' => $topStrengths,
            'top_weaknesses' => $topWeaknesses,
            'overall_performance' => $this->evaluateOverallPerformance($averageMastery),
        ];
    }

    /**
     * 生成智能出卷推荐依据
     * 基于文档中的推荐优先级算法
     */
    private function generateSmartQuizRecommendation(array $updatedMastery): array
    {
        $recommendations = [];

        // 只对子节点生成推荐，忽略父节点
        foreach ($updatedMastery as $kpId => $data) {
            // 跳过父节点
            if ($data['is_parent'] ?? false) {
                continue;
            }

            $mastery = $data['current_mastery'];
            // 【公司要求】移除置信度，只使用掌握度计算推荐
            $weight = $data['weight'];

            // 推荐优先级 = (1 - 掌握度) * 重要性 * 覆盖需求
            // 重要性可以根据知识点在中考/阶段考试中的权重，这里简化为1.0
            $importance = 1.0;

            // 覆盖需求：最近没考过或考得少，值大
            $coverageNeed = max(1.0, 1.5 - ($weight / 10));

            $priority = (1 - $mastery) * $importance * $coverageNeed;

            $recommendations[] = [
                'kp_id' => $kpId,
                'current_mastery' => $mastery,
                'priority' => $priority,
                'recommended_questions' => $this->calculateRecommendedQuestions($mastery),
                'focus_type' => $this->determineFocusType($mastery),
            ];
        }

        // 按优先级排序
        usort($recommendations, fn ($a, $b) => $b['priority'] <=> $a['priority']);

        // 控制难度节奏：40%巩固型 + 40%修补型 + 20%挑战型
        $totalRecommendations = count($recommendations);
        $consolidation = array_slice($recommendations, 0, intval($totalRecommendations * 0.4));
        $remediation = array_slice($recommendations, intval($totalRecommendations * 0.4), intval($totalRecommendations * 0.4));
        $challenge = array_slice($recommendations, intval($totalRecommendations * 0.8));

        return [
            'priority_list' => $recommendations,
            'quiz_structure' => [
                'consolidation_type' => $consolidation,
                'remediation_type' => $remediation,
                'challenge_type' => $challenge,
            ],
            'total_recommended_questions' => array_sum(array_column($recommendations, 'recommended_questions')),
        ];
    }

    /**
     * 保存考试答题记录
     *
     * 入参格式示例：
     * {
     *   "question_bank_id": "12979",
     *   "student_answer": "C",
     *   "is_correct": [0],         // 数组长度决定步骤数，0=错误，1=正确
     *   "teacher_comment": null
     * }
     *
     * is_correct 数组说明：
     * - 单选题：[1] 或 [0]，长度为1
     * - 填空题：[1, 0, 1]，每个空一个元素
     * - 简答题：[1, 1, 0, 1]，每个得分步骤一个元素
     */

    /**
     * 保存错题记录
     *
     * @param  string  $studentId  学生ID
     * @param  string  $questionId  题目ID
     * @param  string  $examId  考试ID
     * @param  array  $question  题目数据
     * @param  array|null  $kpMapping  知识点映射（数组格式：[kp_id1, kp_id2] 或 null）
     */
    private function saveMistakeRecord(string $studentId, string $questionId, string $examId, array $question, ?array $kpMapping): void
    {
        try {
            // 如果 $kpMapping 是数组，说明是多个 kp_id
            // 如果是关联数组，说明是单个 kpMapping（兼容旧调用）
            $kpIds = null;
            if (is_array($kpMapping)) {
                // 检查是数组的数组（多个kp_id）还是关联数组（单个kpMapping）
                if (isset($kpMapping[0])) {
                    // 数组的数组：[[kp_id: '...'], [kp_id: '...']]
                    $kpIds = array_column($kpMapping, 'kp_id');
                } else {
                    // 关联数组：[kp_id: '...']
                    $kpIds = [$kpMapping['kp_id']];
                }
            }

            $payload = [
                'student_id' => $studentId,
                'question_id' => $questionId,
                'paper_id' => $examId,
                'my_answer' => $question['student_answer'] ?? null,
                'correct_answer' => null, // 可以从题目表获取
                'question_text' => null,  // 可以从题目表获取
                'knowledge_point' => null, // 不保存name，只保存kp_ids
                'kp_ids' => $kpIds, // 保存为数组格式
                'source' => $examId, // 来源标记使用卷子ID
                'happened_at' => now(),
            ];

            $result = $this->mistakeBookService->createMistake($payload);

            if (($result['duplicate'] ?? false) === false) {
                Log::debug('错题记录保存成功', [
                    'student_id' => $studentId,
                    'question_id' => $questionId,
                    'mistake_id' => $result['mistake_id'] ?? null,
                ]);
            }
        } catch (\Exception $e) {
            Log::warning('错题记录保存失败（不中断主流程）', [
                'student_id' => $studentId,
                'question_id' => $questionId,
                'exam_id' => $examId,
                'error' => $e->getMessage(),
            ]);
        }
    }

    /**
     * 保存答题记录（优化版：批量INSERT）
     *
     * @param  array  $examData  考试数据
     * @param  array  $questionMappings  已批量查询的知识点映射，避免N+1
     */
    private function saveExamAnswerRecords(array $examData, array $questionMappings = []): array
    {
        // 【修复】确保类型正确，避免 SQL 类型转换问题
        $studentId = (string) $examData['student_id'];
        $examId = (string) $examData['paper_id'];
        $now = now();

        // 【优化】收集所有要插入的记录，最后批量INSERT
        $stepsToInsert = [];
        $questionsToInsert = [];
        $mistakesToSave = []; // 收集错题记录

        foreach ($examData['questions'] as $question) {
            $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
            if (empty($questionId)) {
                continue;
            }

            // 【优化】使用传入的映射，不再查询数据库
            $kpMappings = $questionMappings[$questionId]['kp_mapping'] ?? [];

            $isCorrectArray = $question['is_correct'] ?? [];
            if (! is_array($isCorrectArray)) {
                $isCorrectArray = [$isCorrectArray ? 1 : 0];
            }
            $stepCount = count($isCorrectArray);

            if ($stepCount > 1 || ! empty($kpMappings)) {
                // 多步骤题目：收集步骤记录
                $scorePerStep = ($question['score'] ?? 0) / max($stepCount, 1);
                $hasMistake = false;
                $allErrorKpCodes = [];

                foreach ($isCorrectArray as $stepIndex => $isCorrect) {
                    $isCorrectBool = (int) $isCorrect === 1;

                    if (! empty($kpMappings)) {
                        foreach ($kpMappings as $kpMapping) {
                            $stepsToInsert[] = [
                                'student_id' => $studentId,
                                'exam_id' => $examId,
                                'question_id' => $questionId,
                                'step_index' => $stepIndex,
                                'kp_id' => $kpMapping['kp_id'],
                                'is_correct' => $isCorrectBool ? 1 : 0,
                                'step_score' => $isCorrectBool ? $scorePerStep : 0,
                                'created_at' => $now,
                                'updated_at' => $now,
                            ];

                            if (! $isCorrectBool) {
                                $hasMistake = true;
                                $allErrorKpCodes[] = $kpMapping['kp_id'];
                            }
                        }
                    } else {
                        $stepsToInsert[] = [
                            'student_id' => $studentId,
                            'exam_id' => $examId,
                            'question_id' => $questionId,
                            'step_index' => $stepIndex,
                            'kp_id' => null,
                            'is_correct' => $isCorrectBool ? 1 : 0,
                            'step_score' => $isCorrectBool ? $scorePerStep : 0,
                            'created_at' => $now,
                            'updated_at' => $now,
                        ];

                        if (! $isCorrectBool) {
                            $hasMistake = true;
                        }
                    }
                }

                // 收集错题记录
                if ($hasMistake) {
                    $uniqueKpCodes = array_values(array_unique($allErrorKpCodes));
                    $mistakesToSave[] = [
                        'questionId' => $questionId,
                        'question' => $question,
                        'kpMappings' => array_map(fn ($code) => ['kp_id' => $code], $uniqueKpCodes),
                    ];
                }
            } else {
                // 单步骤题目：收集题目级记录
                $questionsToInsert[] = [
                    'student_id' => $studentId,
                    'exam_id' => $examId,
                    'question_id' => $questionId,
                    'score_obtained' => $question['score_obtained'] ?? 0,
                    'max_score' => $question['score'] ?? 0,
                    'created_at' => $now,
                    'updated_at' => $now,
                ];

                // 收集错题记录
                if (($question['score_obtained'] ?? 0) <= 0) {
                    $mistakesToSave[] = [
                        'questionId' => $questionId,
                        'question' => $question,
                        'kpMappings' => ! empty($kpMappings)
                            ? array_map(fn ($m) => ['kp_id' => $m['kp_id']], $kpMappings)
                            : null,
                    ];
                }
            }
        }

        // 判断是否有变更，避免重复删除/插入
        $stepsChanged = $this->hasAnswerStepsChanged($studentId, $examId, $stepsToInsert);
        $questionsChanged = $this->hasAnswerQuestionsChanged($studentId, $examId, $questionsToInsert);

        if ($stepsChanged || $questionsChanged) {
            // 先清理该考试的所有答题记录（支持重复提交）
            try {
                if ($questionsChanged) {
                    DB::connection('mysql')->table('student_answer_questions')
                        ->where('student_id', '=', $studentId)
                        ->where('exam_id', '=', $examId)
                        ->delete();
                }

                if ($stepsChanged) {
                    DB::connection('mysql')->table('student_answer_steps')
                        ->where('student_id', '=', $studentId)
                        ->where('exam_id', '=', $examId)
                        ->delete();
                }

                Log::info('清理旧答题记录成功', [
                    'student_id' => $studentId,
                    'exam_id' => $examId,
                    'steps_changed' => $stepsChanged,
                    'questions_changed' => $questionsChanged,
                ]);
            } catch (\Exception $e) {
                // 清理失败时抛出异常，避免后续插入重复数据
                Log::error('清理旧答题记录失败', [
                    'student_id' => $studentId,
                    'exam_id' => $examId,
                    'error' => $e->getMessage(),
                ]);
                throw $e;
            }

            // 【优化】批量 INSERT（每500条一批，避免超过MySQL限制）
            try {
                if ($stepsChanged && ! empty($stepsToInsert)) {
                    foreach (array_chunk($stepsToInsert, 500) as $chunk) {
                        DB::connection('mysql')->table('student_answer_steps')->insert($chunk);
                    }
                }

                if ($questionsChanged && ! empty($questionsToInsert)) {
                    foreach (array_chunk($questionsToInsert, 500) as $chunk) {
                        DB::connection('mysql')->table('student_answer_questions')->insert($chunk);
                    }
                }
            } catch (\Exception $e) {
                Log::error('批量保存答题记录失败', [
                    'student_id' => $studentId,
                    'exam_id' => $examId,
                    'error' => $e->getMessage(),
                ]);
            }
        }

        // 保存错题记录（批量处理，避免逐条写入）
        if (! empty($mistakesToSave)) {
            $payloads = [];
            foreach ($mistakesToSave as $mistake) {
                $kpIds = null;
                if (is_array($mistake['kpMappings'])) {
                    $kpIds = isset($mistake['kpMappings'][0])
                        ? array_column($mistake['kpMappings'], 'kp_id')
                        : [$mistake['kpMappings']['kp_id'] ?? null];
                }

                $payloads[] = [
                    'student_id' => $studentId,
                    'question_id' => $mistake['questionId'],
                    'paper_id' => $examId,
                    'my_answer' => $mistake['question']['student_answer'] ?? null,
                    'correct_answer' => null,
                    'question_text' => null,
                    'knowledge_point' => null,
                    'kp_ids' => $kpIds,
                    'source' => $examId,
                    'happened_at' => now(),
                ];
            }

            $this->mistakeBookService->createMistakesBatch($payloads);
        }

        Log::info('答题记录保存完成', [
            'student_id' => $studentId,
            'exam_id' => $examId,
            'total_questions' => count($examData['questions']),
            'steps_saved' => count($stepsToInsert),
            'questions_saved' => count($questionsToInsert),
            'steps_changed' => $stepsChanged,
            'questions_changed' => $questionsChanged,
        ]);

        return [
            'steps_changed' => $stepsChanged,
            'questions_changed' => $questionsChanged,
        ];
    }

    /**
     * 同步更新 paper_questions 的判分字段
     * 适配 /api/exam-answer-analysis：保持题目判分与分析数据一致
     */
    private function syncPaperQuestionGrading(array $examData): void
    {
        $paperId = (string) ($examData['paper_id'] ?? '');
        if ($paperId === '' || empty($examData['questions']) || !is_array($examData['questions'])) {
            return;
        }

        $now = now();
        $updated = 0;
        $processedQuestionIds = [];
        foreach ($examData['questions'] as $question) {
            $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? null;
            if (empty($questionId)) {
                continue;
            }
            $questionId = (string) $questionId;
            // 同一题只更新一次，避免双字段命中导致重复更新
            if (isset($processedQuestionIds[$questionId])) {
                continue;
            }
            $processedQuestionIds[$questionId] = true;

            $isCorrectArray = $question['is_correct'] ?? [];
            if (! is_array($isCorrectArray)) {
                $isCorrectArray = [$isCorrectArray ? 1 : 0];
            }
            $totalSteps = count($isCorrectArray);
            $correctSteps = array_sum(array_map(fn ($v) => (int) $v === 1 ? 1 : 0, $isCorrectArray));
            $scoreRatio = $totalSteps > 0 ? round($correctSteps / $totalSteps, 4) : null;
            $isFullyCorrect = $totalSteps > 0 ? ($correctSteps === $totalSteps ? 1 : 0) : null;
            $scoreObtained = $question['score_obtained'] ?? null;

            $payload = [
                'graded_at' => $now,
            ];
            if ($isFullyCorrect !== null) {
                $payload['is_correct'] = $isFullyCorrect;
            }
            if ($scoreRatio !== null) {
                $payload['score_ratio'] = $scoreRatio;
            }
            if ($scoreObtained !== null) {
                $payload['score_obtained'] = $scoreObtained;
            }
            if (array_key_exists('student_answer', $question)) {
                $payload['student_answer'] = $question['student_answer'];
            }
            if (array_key_exists('teacher_comment', $question)) {
                $payload['teacher_comment'] = $question['teacher_comment'];
            }

            // 关键：不再依赖 paper_questions.id（部分库该字段为空），改为业务键匹配更新
            $affected = DB::connection('mysql')->table('paper_questions')
                ->where('paper_id', $paperId)
                ->where(function ($q) use ($questionId) {
                    $q->where('question_bank_id', $questionId)
                        ->orWhere('question_id', $questionId);
                })
                ->update($payload);

            $updated += $affected;
        }

        if ($updated > 0) {
            DB::connection('mysql')->table('papers')
                ->where('paper_id', $paperId)
                ->update([
                    'status' => 'completed',
                    'completed_at' => $now,
                    'updated_at' => $now,
                ]);
        }

        Log::info('paper_questions 判分同步完成', [
            'paper_id' => $paperId,
            'input_question_count' => count($examData['questions']),
            'processed_question_count' => count($processedQuestionIds),
            'updated_rows' => $updated,
        ]);
    }

    /**
     * 判断答题步骤记录是否发生变化
     */
    private function hasAnswerStepsChanged(string $studentId, string $examId, array $newSteps): bool
    {
        $existing = DB::connection('mysql')
            ->table('student_answer_steps')
            ->where('student_id', $studentId)
            ->where('exam_id', $examId)
            ->get(['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'])
            ->map(fn ($row) => (array) $row)
            ->toArray();

        return $this->buildRecordsHash($existing, ['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'], ['step_score'])
            !== $this->buildRecordsHash($newSteps, ['student_id', 'exam_id', 'question_id', 'step_index', 'kp_id', 'is_correct', 'step_score'], ['step_score']);
    }

    /**
     * 判断题目级答题记录是否发生变化
     */
    private function hasAnswerQuestionsChanged(string $studentId, string $examId, array $newQuestions): bool
    {
        $existing = DB::connection('mysql')
            ->table('student_answer_questions')
            ->where('student_id', $studentId)
            ->where('exam_id', $examId)
            ->get(['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'])
            ->map(fn ($row) => (array) $row)
            ->toArray();

        return $this->buildRecordsHash($existing, ['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'], ['score_obtained', 'max_score'])
            !== $this->buildRecordsHash($newQuestions, ['student_id', 'exam_id', 'question_id', 'score_obtained', 'max_score'], ['score_obtained', 'max_score']);
    }

    /**
     * 构建记录哈希，用于判断是否变化
     */
    private function buildRecordsHash(array $rows, array $fields, array $numericFields = []): string
    {
        if (empty($rows)) {
            return '[]';
        }

        $normalized = [];
        $numericFieldMap = array_fill_keys($numericFields, true);

        foreach ($rows as $row) {
            $item = [];
            foreach ($fields as $field) {
                $value = $row[$field] ?? null;
                if ($value !== null && isset($numericFieldMap[$field]) && is_numeric($value)) {
                    $value = sprintf('%.4F', (float) $value);
                }
                $item[$field] = $value;
            }
            $normalized[] = $item;
        }

        usort($normalized, fn ($a, $b) => json_encode($a) <=> json_encode($b));

        return md5(json_encode($normalized));
    }

    /**
     * 保存分析结果并创建掌握度快照
     */
    private function saveAnalysisResult(string $studentId, string $paperId, array $result): void
    {
        // 【修复】支持重复分析：先删除旧的分析结果
        DB::connection('mysql')->table('exam_analysis_results')
            ->where('student_id', $studentId)
            ->where('paper_id', $paperId)
            ->delete();

        // 插入新的分析结果
        DB::connection('mysql')->table('exam_analysis_results')->insert([
            'student_id' => $studentId,
            'paper_id' => $paperId,
            'analysis_data' => json_encode($result),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        Log::info('分析结果保存完成', [
            'student_id' => $studentId,
            'paper_id' => $paperId,
            'data_size' => strlen(json_encode($result)),
        ]);

        // 【新增】异步生成学情分析PDF
        try {
            Log::info('开始异步生成学情分析PDF', [
                'student_id' => $studentId,
                'paper_id' => $paperId,
            ]);

            // 使用队列异步生成PDF，避免阻塞主流程
            dispatch(new \App\Jobs\GenerateAnalysisPdfJob($paperId, $studentId, null));

            Log::info('PDF生成任务已加入队列', [
                'student_id' => $studentId,
                'paper_id' => $paperId,
            ]);
        } catch (\Exception $e) {
            Log::error('PDF生成任务加入队列失败', [
                'student_id' => $studentId,
                'paper_id' => $paperId,
                'error' => $e->getMessage(),
            ]);
        }
    }

    /**
     * 创建知识点掌握度快照
     * 【集成】使用LocalAIAnalysisService的快照功能
     *
     * 快照用途：
     * 1. 追踪学生掌握度变化趋势
     * 2. 生成学情报告时对比历史数据
     * 3. 为智能出卷提供决策依据
     */
    private function createMasterySnapshot(string $studentId, string $paperId, array $analysisResult): ?array
    {
        try {
            // 计算快照数据
            $masteryVector = $analysisResult['mastery_vector'] ?? [];
            $overallMastery = 0;
            $weakCount = 0;
            $strongCount = 0;

            foreach ($masteryVector as $kpData) {
                $mastery = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
                $overallMastery += $mastery;

                if ($mastery < 0.6) {
                    $weakCount++;
                } elseif ($mastery >= 0.85) {
                    $strongCount++;
                }
            }

            $kpCount = count($masteryVector);
            $overallMastery = $kpCount > 0 ? round($overallMastery / $kpCount, 4) : 0;

            // Get all existing mastery records from database (as baseline)
            // Use DB::table to avoid Eloquent accessor converting numbers to strings
            $studentMasteries = DB::table('student_knowledge_mastery')
                ->where('student_id', $studentId)
                ->get(['kp_code', 'mastery_level']);

            $currentMastery = [];
            foreach ($studentMasteries as $record) {
                $currentMastery[$record->kp_code] = (float) ($record->mastery_level ?? 0);
            }

            // Update with newly calculated mastery values from analysis result
            foreach ($masteryVector as $kpData) {
                $kpCode = $kpData['kp_id'] ?? null;
                if (! $kpCode) {
                    continue;
                }
                $analysisLevel = $kpData['current_mastery'] ?? $kpData['mastery'] ?? 0;
                // Use new analysis value if it's higher, or if there was no previous value
                if (! isset($currentMastery[$kpCode]) || $analysisLevel > $currentMastery[$kpCode]) {
                    $currentMastery[$kpCode] = $analysisLevel;
                }
            }

            // 生成快照ID
            $snapshotId = 'snap_'.$paperId.'_'.now()->format('YmdHis').'_'.substr(uniqid(), -4);

            // 保存到快照表
            DB::connection('mysql')->table('knowledge_point_mastery_snapshots')->insert([
                'snapshot_id' => $snapshotId,
                'student_id' => $studentId,
                'paper_id' => $paperId,
                'answer_record_id' => null,
                'mastery_data' => json_encode($masteryVector),
                'current_mastery' => json_encode($currentMastery),
                'overall_mastery' => $overallMastery,
                'weak_knowledge_points_count' => $weakCount,
                'strong_knowledge_points_count' => $strongCount,
                'snapshot_time' => now(),
                'analysis_id' => null,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            Log::info('掌握度快照创建成功', [
                'snapshot_id' => $snapshotId,
                'student_id' => $studentId,
                'paper_id' => $paperId,
                'overall_mastery' => $overallMastery,
                'weak_count' => $weakCount,
                'strong_count' => $strongCount,
            ]);

            // 计算变化
            $lastSnapshot = DB::connection('mysql')->table('knowledge_point_mastery_snapshots')
                ->where('student_id', $studentId)
                ->where('snapshot_id', '<>', $snapshotId)
                ->orderBy('snapshot_time', 'desc')
                ->first();

            $gainCount = $lossCount = 0;
            $overallChange = 0;
            $compareCount = 0;
            $changeAverage = 0;

            if ($lastSnapshot && ! empty($lastSnapshot->current_mastery)) {
                $lastCurrentMastery = json_decode($lastSnapshot->current_mastery, true);
                if (is_array($lastCurrentMastery)) {
                    foreach ($currentMastery as $kp => $value) {
                        $prev = $lastCurrentMastery[$kp] ?? null;
                        if ($prev === null) {
                            $gainCount++;
                        } elseif ($value > $prev) {
                            $gainCount++;
                        } elseif ($value < $prev) {
                            $lossCount++;
                        }
                        if ($prev !== null) {
                            $overallChange += $value - $prev;
                            $compareCount++;
                        }
                    }
                    $changeAverage = $compareCount > 0 ? round($overallChange / $compareCount, 4) : 0;
                    Log::info('掌握度变化', [
                        'student_id' => $studentId,
                        'paper_id' => $paperId,
                        'snapshot_id' => $snapshotId,
                        'gain_count' => $gainCount,
                        'loss_count' => $lossCount,
                        'overall_change' => $changeAverage,
                    ]);
                }
            }

            return [
                'snapshot_id' => $snapshotId,
                'current_mastery' => $currentMastery,
                'overall_mastery' => $overallMastery,
                'gain_count' => $gainCount,
                'loss_count' => $lossCount,
                'overall_change' => $changeAverage,
            ];

        } catch (\Exception $e) {
            // 快照创建失败不影响主流程
            Log::warning('掌握度快照创建失败', [
                'student_id' => $studentId,
                'paper_id' => $paperId,
                'error' => $e->getMessage(),
            ]);

            return null;
        }
    }

    /**
     * 判断掌握度趋势
     */
    /**
     * 评估表现水平
     */
    private function evaluatePerformanceLevel(float $mastery): string
    {
        if ($mastery >= 0.85) {
            return 'excellent';
        } elseif ($mastery >= 0.70) {
            return 'good';
        } elseif ($mastery >= 0.50) {
            return 'fair';
        } else {
            return 'poor';
        }
    }

    /**
     * 生成题目表现总结
     */
    private function generateQuestionPerformanceSummary(array $question, array $stepAnalysis): string
    {
        if (empty($stepAnalysis)) {
            return '整题作答';
        }

        $correctSteps = count(array_filter($stepAnalysis, fn ($s) => $s['is_correct']));
        $totalSteps = count($stepAnalysis);

        if ($correctSteps === $totalSteps) {
            return '所有步骤正确';
        } elseif ($correctSteps > 0) {
            return "部分正确 ({$correctSteps}/{$totalSteps} 步骤正确)";
        } else {
            return '所有步骤错误';
        }
    }

    /**
     * 生成知识点建议
     */
    private function generateKnowledgePointRecommendation(array $data): string
    {
        $mastery = $data['mastery'];

        if ($mastery >= 0.85) {
            return '掌握良好，可安排综合练习';
        } elseif ($mastery >= 0.70) {
            return '基本掌握，建议加强练习';
        } elseif ($mastery >= 0.50) {
            return '需要重点练习，建议安排专项训练';
        } else {
            return '薄弱知识点，建议系统学习和大量练习';
        }
    }

    /**
     * 评估整体表现
     */
    private function evaluateOverallPerformance(float $averageMastery): string
    {
        if ($averageMastery >= 0.85) {
            return '优秀';
        } elseif ($averageMastery >= 0.70) {
            return '良好';
        } elseif ($averageMastery >= 0.50) {
            return '一般';
        } else {
            return '需加强';
        }
    }

    /**
     * 计算推荐题目数量
     */
    private function calculateRecommendedQuestions(float $mastery): int
    {
        if ($mastery >= 0.85) {
            return 1; // 巩固型：1题
        } elseif ($mastery >= 0.50) {
            return 2; // 修补型：2题
        } else {
            return 3; // 挑战型：3题
        }
    }

    /**
     * 确定重点类型
     */
    private function determineFocusType(float $mastery): string
    {
        if ($mastery >= 0.70 && $mastery < 0.85) {
            return 'consolidation'; // 巩固型
        } elseif ($mastery < 0.70) {
            return 'remediation'; // 修补型
        } else {
            return 'challenge'; // 挑战型
        }
    }

    /**
     * 自动计算题目分数并补充未提交的题目
     *
     * 功能：
     * 1. 从 paper_questions 表获取卷子的所有题目
     * 2. 补充未提交的题目（is_correct 默认为 [0]，表示错误）
     * 3. 自动计算 score 和 score_obtained
     *
     * @param  array  $questions  用户提交的题目列表
     * @param  string  $paperId  卷子ID
     * @return array 完整的题目列表（包含未提交的题目）
     */
    private function autoCalculateScores(array $questions, string $paperId = ''): array
    {
        // 获取已提交题目的ID集合
        $submittedQuestionIds = [];
        foreach ($questions as $question) {
            $qid = $question['question_id'] ?? $question['question_bank_id'] ?? null;
            if ($qid) {
                $submittedQuestionIds[$qid] = true;
            }
        }

        // 从 paper_questions 表获取卷子的所有题目
        if (! empty($paperId)) {
            try {
                $paperQuestions = DB::connection('mysql')
                    ->table('paper_questions')
                    ->where('paper_id', $paperId)
                    ->get(['question_bank_id', 'question_id', 'score']);

                foreach ($paperQuestions as $pq) {
                    // 优先用 question_bank_id，其次用 question_id
                    $questionId = $pq->question_bank_id ?? $pq->question_id ?? null;
                    if (empty($questionId)) {
                        continue;
                    }
                    if (isset($pq->score)) {
                        $scoreMap[$questionId] = (float) $pq->score;
                    }

                    // 如果该题目未提交，补充进去
                    if (! isset($submittedQuestionIds[$questionId])) {
                        $defaultScore = $pq->score ? floatval($pq->score) : 2.0;
                        $questions[] = [
                            'question_id' => $questionId,
                            'student_answer' => null,
                            'is_correct' => [1], // 未提交默认为正确
                            'teacher_comment' => null,
                            'score' => $defaultScore,
                            'score_obtained' => $defaultScore, // 正确则得满分
                        ];

                        Log::debug('补充未提交的题目', [
                            'paper_id' => $paperId,
                            'question_id' => $questionId,
                            'default_score' => $pq->score ?? 2.0,
                        ]);
                    }
                }
            } catch (\Exception $e) {
                Log::warning('获取卷子题目列表失败', [
                    'paper_id' => $paperId,
                    'error' => $e->getMessage(),
                ]);
            }
        }

        // 为已提交的题目计算分数
        foreach ($questions as &$question) {
            $questionId = $question['question_id'] ?? $question['question_bank_id'] ?? '';

            // 如果用户没有提供 score，尝试从数据库获取或使用默认值
            if (! isset($question['score'])) {
                $question['score'] = $scoreMap[$questionId] ?? 2.0;
            }

            // 如果用户没有提供 score_obtained，根据 is_correct 计算
            if (! isset($question['score_obtained'])) {
                $question['score_obtained'] = $this->calculateScoreObtained(
                    $question['score'] ?? 0,
                    $question['is_correct'] ?? []
                );
            }

            if (config('app.debug')) {
                Log::debug('自动计算分数', [
                    'question_id' => $questionId,
                    'default_score' => $question['score'],
                    'score_obtained' => $question['score_obtained'],
                    'is_correct' => $question['is_correct'] ?? [],
                ]);
            }
        }

        return $questions;
    }

    /**
     * 获取题目默认分数
     */
    private function getQuestionDefaultScore(string $questionId): float
    {
        if (empty($questionId)) {
            return 2.0; // 默认分数
        }

        try {
            // 尝试从题库获取题目分数
            $question = DB::connection('mysql')
                ->table('questions')
                ->where('id', $questionId)
                ->orWhere('question_code', $questionId)
                ->first();

            if ($question && isset($question->score)) {
                return (float) $question->score;
            }

            // 如果没有找到，根据题目ID生成一个合理的默认分数
            // 这里可以根据需要调整默认分数逻辑
            return 2.0;

        } catch (\Exception $e) {
            Log::warning('获取题目默认分数失败，使用默认值', [
                'question_id' => $questionId,
                'error' => $e->getMessage(),
            ]);

            return 2.0;
        }
    }

    /**
     * 根据 is_correct 数组计算得分
     *
     * @param  float  $totalScore  总分
     * @param  array  $isCorrect  正确性数组 [0, 1, 1] 表示第1题错误，第2、3题正确
     * @return float 得分
     */
    private function calculateScoreObtained(float $totalScore, array $isCorrect): float
    {
        if (empty($isCorrect)) {
            return 0.0;
        }

        $correctCount = array_sum($isCorrect);
        $totalCount = count($isCorrect);

        if ($totalCount === 0) {
            return 0.0;
        }

        // 按正确率计算得分
        $scoreRatio = $correctCount / $totalCount;

        return round($totalScore * $scoreRatio, 2);
    }
}
