<?php

namespace App\Services;

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

/**
 * 考试答题分析服务（步骤级分析）
 * 基于卷子分析思考文档的思路实现
 *
 * 核心流程：
 * 1. 接收卷子ID和每道题的对错、简答题的分步骤对错
 * 2. 将原子信息映射到知识点/技能
 * 3. 计算知识点掌握度向量
 * 4. 生成详细分析报告
 * 5. 提供智能出卷推荐依据
 */
class ExamAnswerAnalysisService
{
    public function __construct(
        private readonly MasteryCalculator $masteryCalculator,
        private readonly KnowledgeMasteryService $knowledgeMasteryService,
        private readonly LocalAIAnalysisService $aiAnalysisService
    ) {}

    /**
     * 分析考试答题数据
     *
     * @param array $examData 考试数据
     * [
     *   'paper_id' => 'exam_001',
     *   'student_id' => 'student_001',
     *   'questions' => [
     *     [
     *       'question_id' => 'Q1',
     *       'score' => 5,
     *       'score_obtained' => 5,
     *       'steps' => [
     *         ['step_index' => 1, 'is_correct' => true, 'kp_id' => 'K-SQRT-SIMPLE'],
     *         ['step_index' => 2, 'is_correct' => true, 'kp_id' => 'K-NUM-ADD-SUB']
     *       ]
     *     ]
     *   ]
     * ]
     *
     * @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'];
        $questions = $examData['questions'] ?? [];

        // 0. 自动计算分数（如果用户未提供）
        $questions = $this->autoCalculateScores($questions);

        // 1. 获取学案基准难度
        $examBaseDifficulty = $this->getExamBaseDifficulty($examData['paper_id'] ?? '');

        // 2. 保存答题记录到数据库
        $this->saveExamAnswerRecords($examData);

        // 3. 获取题目知识点映射
        $questionMappings = $this->getQuestionKnowledgeMappings($questions);

        // 4. 计算每个知识点的加权掌握度（传入学案基准难度）
        $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,
        ];

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

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

        return $analysisResult;
    }

    /**
     * 获取学案基准难度（映射为1-4级）
     */
    private function getExamBaseDifficulty(string $paperId): ?int
    {
        if (empty($paperId)) {
            return null;
        }

        try {
            // 从试卷表获取difficulty_category
            $paper = DB::table('papers')
                ->where('paper_id', $paperId)
                ->first();

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

            $difficultyCategory = $paper->difficulty_category ?? '中等';

            // 映射为1-4级（筑基、提分、培优、竞赛）
            return match (strtolower($difficultyCategory)) {
                '筑基', 'easy', 'foundation', '1' => 1,
                '提分', 'medium', 'improvement', '2' => 2,
                '培优', 'hard', 'excellent', 'difficult', '3' => 3,
                '竞赛', 'competition', 'very hard', 'very difficult', '4' => 4,
                default => 2, // 默认提分
            };

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

    /**
     * 获取题目知识点映射
     */
    private function getQuestionKnowledgeMappings(array $questions): array
    {
        $mappings = [];
        $failedQuestions = [];

        // 直接从题目数据中提取知识点信息（不再调用外部服务）
        foreach ($questions as $question) {
            $questionId = $question['question_id'] ?? null;
            if (!$questionId) continue;

            // 提取知识点信息（优先使用请求数据中的字段）
            $kpMapping = [];

            // 尝试多个可能的知识点字段
            $kpCode = $question['kp_code']
                ?? $question['knowledge_point']
                ?? $question['kp_code']
                ?? null;

            // 如果请求中没有知识点信息，从数据库自动获取
            if (empty($kpCode)) {
                $dbKpInfo = $this->getQuestionKnowledgePointFromDb($questionId);
                if ($dbKpInfo) {
                    $kpMapping[] = [
                        'kp_id' => $dbKpInfo['kp_id'],
                        'kp_name' => $dbKpInfo['kp_name'],
                        'weight' => 1.0
                    ];
                    Log::debug('从数据库获取题目知识点', [
                        'question_id' => $questionId,
                        'kp_id' => $dbKpInfo['kp_id']
                    ]);
                }
            } else {
                $kpMapping[] = [
                    'kp_id' => $kpCode,
                    'kp_name' => $question['kp_name'] ?? $kpCode,
                    'weight' => 1.0
                ];
            }

            // 如果仍然没有知识点信息，跳过该题目
            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)
        ]);

        return $mappings;
    }

    /**
     * 从数据库获取题目的知识点信息
     */
    private function getQuestionKnowledgePointFromDb(string $questionId): ?array
    {
        try {
            // 优先从 MySQL 的 questions 表获取
            $question = DB::connection('mysql')
                ->table('questions')
                ->where('id', $questionId)
                ->orWhere('question_code', $questionId)
                ->first();

            $kpCode = null;
            if ($question) {
                // 尝试从 kp_code 或 knowledge_point 字段获取
                $kpCode = $question->kp_code
                    ?? $question->knowledge_point
                    ?? $question->knowledge_points
                    ?? null;
            }

            // 如果questions表中没有，从knowledge_points表查找
            if (!$kpCode) {
                $kpCode = $questionId; // 假设question_id就是kp_code
            }

            // 从 knowledge_points 表获取知识点详细信息（包含中文名称）
            $kpInfo = DB::connection('mysql')
                ->table('knowledge_points')
                ->where('kp_code', $kpCode)
                ->first();

            if ($kpInfo) {
                Log::debug('从knowledge_points表获取知识点', [
                    'question_id' => $questionId,
                    'kp_code' => $kpCode,
                    'kp_name' => $kpInfo->name
                ]);
                return [
                    'kp_id' => $kpCode,
                    'kp_name' => $kpInfo->name
                ];
            }

            // 备选：从 QuestionBank API 获取知识点
            $questionBankInfo = $this->getQuestionFromQuestionBank($questionId);
            if ($questionBankInfo && !empty($questionBankInfo['knowledge_points'])) {
                $apiKpCode = $questionBankInfo['knowledge_points'][0]['code'] ?? null;
                if ($apiKpCode) {
                    // 尝试从 knowledge_points 表获取中文名称
                    $apiKpInfo = DB::connection('mysql')
                        ->table('knowledge_points')
                        ->where('kp_code', $apiKpCode)
                        ->first();

                    return [
                        'kp_id' => $apiKpCode,
                        'kp_name' => $apiKpInfo->name ?? ($questionBankInfo['knowledge_points'][0]['name'] ?? $apiKpCode)
                    ];
                }
            }

            // 最后备选：使用kpCode作为名称
            if ($kpCode) {
                Log::warning('未找到知识点中文名称，使用编码作为名称', [
                    'question_id' => $questionId,
                    'kp_code' => $kpCode
                ]);
                return [
                    'kp_id' => $kpCode,
                    'kp_name' => $kpCode
                ];
            }

            return null;

        } catch (\Exception $e) {
            Log::warning('从数据库获取题目知识点失败', [
                'question_id' => $questionId,
                'error' => $e->getMessage()
            ]);
            return null;
        }
    }

    /**
     * 从 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;
        }
    }

    /**
     * 计算知识点掌握度向量
     * 【修复】集成MasteryCalculator的BKT模型进行精确计算
     *
     * 核心算法说明：
     * 1. 从考试答题中提取每个知识点的答题记录
     * 2. 调用MasteryCalculator计算掌握度（包含：正确率、难度加权、时间效率、遗忘曲线）
     * 3. 返回包含掌握度、置信度、趋势等完整信息的向量
     */
    private function calculateKnowledgeMasteryVector(array $questions, array $questionMappings, ?int $examBaseDifficulty = null, ?string $studentId = null): array
    {
        // 按知识点聚合答题记录
        $knowledgeAttempts = [];

        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] ?? null;
            if (!$mapping || !isset($mapping['kp_mapping'])) {
                continue;
            }

            // 构建答题记录（用于MasteryCalculator）
            $attemptRecord = [
                'question_id' => $questionId,
                'is_correct' => $isCorrect,
                'partial_score' => $maxScore > 0 ? $score / $maxScore : 0,
                'question_difficulty' => $question['difficulty'] ?? 0.6,
                'attempt_time_seconds' => $question['time_spent'] ?? 120,
                'completed_at' => now()->toISOString(),
                'created_at' => now()->toISOString(),
            ];

            // 如果有步骤级分析，使用步骤分析
            if (!empty($steps)) {
                foreach ($steps as $step) {
                    $kpId = $step['kp_id'];
                    if (empty($kpId)) {
                        Log::warning('ExamAnswerAnalysisService: 步骤缺少知识点ID', [
                            'question_id' => $questionId,
                            'step' => $step
                        ]);
                        continue;
                    }

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

                    // 每个步骤作为独立答题记录
                    $stepAttempt = $attemptRecord;
                    $stepAttempt['is_correct'] = $step['is_correct'];
                    $stepAttempt['step_index'] = $step['step_index'];

                    $knowledgeAttempts[$kpId]['attempts'][] = $stepAttempt;
                    $knowledgeAttempts[$kpId]['step_details'][] = [
                        'question_id' => $questionId,
                        'step_index' => $step['step_index'],
                        'score' => $step['score'] ?? ($maxScore / count($steps)),
                        'is_correct' => $step['is_correct'],
                    ];
                }
            } else {
                // 题目整体分析
                foreach ($mapping['kp_mapping'] as $kpMapping) {
                    $kpId = $kpMapping['kp_id'];

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

                    $knowledgeAttempts[$kpId]['attempts'][] = $attemptRecord;
                    $knowledgeAttempts[$kpId]['step_details'][] = [
                        'question_id' => $questionId,
                        'score' => $score,
                        'max_score' => $maxScore,
                        'is_correct' => $isCorrect,
                    ];
                }
            }
        }

        // 【核心】使用MasteryCalculator计算每个知识点的掌握度
        $masteryVector = [];
        foreach ($knowledgeAttempts as $kpId => $data) {
            $attempts = $data['attempts'];

            // 如果没有学案基准难度，使用默认值2（提分）
            $baseDifficulty = $examBaseDifficulty ?? 2;

            // 调用MasteryCalculator的核心算法（传入学案基准难度）
            // 该算法包含：正确率、难度加权、时间效率、技能熟练度、遗忘曲线衰减
            $masteryResult = $this->masteryCalculator->calculateMasteryLevel(
                $studentId ?? '', // 传递学生ID，用于保存掌握度到数据库
                $kpId,
                $attempts,
                $baseDifficulty
            );

            $masteryVector[$kpId] = [
                'kp_id' => $kpId,
                'mastery' => $masteryResult['mastery'],
                'confidence' => $masteryResult['confidence'],
                'trend' => $masteryResult['trend'],
                '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;
    }

    /**
     * 更新学生掌握度（与历史数据合并）
     */
    private function updateStudentMastery(string $studentId, array $knowledgeMasteryVector): array
    {
        $updatedMastery = [];

        foreach ($knowledgeMasteryVector as $kpId => $data) {
            // 获取历史掌握度
            $historyMastery = DB::connection('mysql')
                ->table('student_knowledge_mastery')
                ->where('student_id', $studentId)
                ->where('kp_code', $kpId)
                ->first();

            $historyMasteryLevel = $historyMastery->mastery_level ?? 0.5;
            $historyWeight = $historyMastery->total_attempts ?? 0;
            $currentWeight = $data['total_attempts'] ?? 1;

            // 合并计算：历史权重 + 当前权重
            $newMastery = $historyWeight > 0
                ? ($historyWeight * $historyMasteryLevel + $currentWeight * $data['mastery'])
                  / ($historyWeight + $currentWeight)
                : $data['mastery'];

            $newConfidence = $data['confidence'];

            // 保存到数据库
            DB::connection('mysql')
                ->table('student_knowledge_mastery')
                ->updateOrInsert(
                    ['student_id' => $studentId, 'kp_code' => $kpId],
                    [
                        'mastery_level' => $newMastery,
                        'confidence_level' => $newConfidence,
                        'total_attempts' => ($historyMastery->total_attempts ?? 0) + 1,
                        'correct_attempts' => ($historyMastery->correct_attempts ?? 0) + intval($data['correct_attempts'] > 0),
                        'mastery_trend' => $this->determineMasteryTrend($historyMasteryLevel, $newMastery),
                        'last_mastery_update' => now(),
                        'updated_at' => now(),
                    ]
                );

            $updatedMastery[$kpId] = [
                'kp_id' => $kpId,
                'current_mastery' => $newMastery,
                'previous_mastery' => $historyMasteryLevel,
                'confidence' => $newConfidence,
                'change' => $newMastery - $historyMasteryLevel,
                'weight' => $currentWeight
            ];
        }

        return $updatedMastery;
    }

    /**
     * 生成题目维度分析（包含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) {
            $analysis[] = [
                'kp_id' => $kpId,
                'mastery_level' => $data['mastery'],
                'confidence_level' => $data['confidence'],
                'performance_in_exam' => $this->evaluatePerformanceLevel($data['mastery']),
                'evidence_count' => count($data['step_details']),
                'step_evidence' => $data['step_details'],
                'recommendation' => $this->generateKnowledgePointRecommendation($data)
            ];
        }

        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' => []
            ];
        }

        // 计算平均掌握度
        $averageMastery = array_sum(array_column($knowledgePoints, 'current_mastery')) / count($knowledgePoints);

        // 掌握度分布
        $mastered = array_filter($knowledgePoints, fn($kp) => $kp['current_mastery'] >= 0.85);
        $good = array_filter($knowledgePoints, fn($kp) => $kp['current_mastery'] >= 0.70 && $kp['current_mastery'] < 0.85);
        $weak = array_filter($knowledgePoints, fn($kp) => $kp['current_mastery'] < 0.70);

        // 排序找出优势和薄弱点
        usort($knowledgePoints, fn($a, $b) => $b['current_mastery'] <=> $a['current_mastery']);
        $topStrengths = array_slice($knowledgePoints, 0, 3);
        $topWeaknesses = array_slice(array_reverse($knowledgePoints), 0, 3);

        return [
            'total_knowledge_points' => count($knowledgePoints),
            '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) {
            $mastery = $data['current_mastery'];
            $confidence = $data['confidence'];
            $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'))
        ];
    }

    /**
     * 保存考试答题记录
     */
    private function saveExamAnswerRecords(array $examData): void
    {
        $studentId = $examData['student_id'];
        $examId = $examData['paper_id'];

        // 【修复】先清理该考试的所有答题记录（支持重复考试）
        DB::connection('mysql')->table('student_answer_questions')
            ->where('student_id', $studentId)
            ->where('exam_id', $examId)
            ->delete();

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

        foreach ($examData['questions'] as $question) {
            $questionId = $question['question_id'];
            $steps = $question['steps'] ?? [];

            // 保存步骤级记录
            if (!empty($steps)) {
                foreach ($steps as $step) {
                    $kpId = $step['kp_id'] ?? null;
                    if (empty($kpId)) {
                        Log::warning('ExamAnswerAnalysisService: 步骤保存缺少知识点ID', [
                            'student_id' => $studentId,
                            'exam_id' => $examId,
                            'question_id' => $questionId,
                            'step_index' => $step['step_index'] ?? 'unknown'
                        ]);
                        continue;
                    }
                    DB::connection('mysql')->table('student_answer_steps')->insert([
                        'student_id' => $studentId,
                        'exam_id' => $examId,
                        'question_id' => $questionId,
                        'step_index' => $step['step_index'],
                        'kp_id' => $kpId,
                        'is_correct' => $step['is_correct'],
                        'step_score' => $step['score'] ?? 0,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            } else {
                // 保存题目级记录
                try {
                    DB::connection('mysql')->table('student_answer_questions')->insertOrIgnore([
                        '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(),
                    ]);
                } catch (\Exception $e) {
                    Log::warning('保存答题记录失败', [
                        'student_id' => $studentId,
                        'exam_id' => $examId,
                        'question_id' => $questionId,
                        'error' => $e->getMessage(),
                    ]);
                }
            }
        }

        Log::info('答题记录保存完成', [
            'student_id' => $studentId,
            'exam_id' => $examId,
            'question_count' => count($examData['questions']),
        ]);
    }

    /**
     * 保存分析结果并创建掌握度快照
     */
    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)),
        ]);

        // 【集成】创建知识点掌握度快照
        $this->createMasterySnapshot($studentId, $paperId, $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): void
    {
        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;

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

            // 保存到快照表
            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),
                '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,
            ]);

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

    /**
     * 判断掌握度趋势
     */
    private function determineMasteryTrend(float $previous, float $current): string
    {
        $change = $current - $previous;

        if ($change > 0.1) {
            return 'improving';
        } elseif ($change < -0.1) {
            return 'declining';
        } else {
            return 'stable';
        }
    }

    /**
     * 评估表现水平
     */
    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'; // 挑战型
        }
    }

    /**
     * 自动计算题目分数
     * 如果用户未提供 score 和 score_obtained，则根据 is_correct 字段自动计算
     *
     * @param array $questions 题目列表
     * @return array 处理后的题目列表
     */
    private function autoCalculateScores(array $questions): array
    {
        foreach ($questions as &$question) {
            // 如果用户没有提供 score，尝试从数据库获取或使用默认值
            if (!isset($question['score'])) {
                $question['score'] = $this->getQuestionDefaultScore($question['question_id'] ?? '');
            }

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

            Log::debug('自动计算分数', [
                'question_id' => $question['question_id'],
                '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);
    }
}
