<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Paper;
use App\Models\PaperQuestion;
use App\Services\LearningAnalyticsService;
use App\Services\ExamPdfExportService;
use App\Services\ExternalIdService;
use App\Services\QuestionBankService;
use App\Services\PaperPayloadService;
use App\Services\TaskManager;
use App\Models\MistakeRecord;
use App\Models\Student;
use App\Models\Teacher;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\URL;

class IntelligentExamController extends Controller
{
    private LearningAnalyticsService $learningAnalyticsService;
    private QuestionBankService $questionBankService;
    private ExamPdfExportService $pdfExportService;
    private PaperPayloadService $paperPayloadService;
    private TaskManager $taskManager;
    private ExternalIdService $externalIdService;

    public function __construct(
        LearningAnalyticsService $learningAnalyticsService,
        QuestionBankService $questionBankService,
        ExamPdfExportService $pdfExportService,
        PaperPayloadService $paperPayloadService,
        TaskManager $taskManager,
        ExternalIdService $externalIdService
    ) {
        $this->learningAnalyticsService = $learningAnalyticsService;
        $this->questionBankService = $questionBankService;
        $this->pdfExportService = $pdfExportService;
        $this->paperPayloadService = $paperPayloadService;
        $this->taskManager = $taskManager;
        $this->externalIdService = $externalIdService;
    }

    /**
     * 外部API：生成智能试卷（异步模式）
     * 立即返回任务ID，PDF生成在后台进行，完成后通过回调通知
     */
    public function store(Request $request): JsonResponse
    {
        // 优先从body获取数据，不使用query params
        $payload = $request->json()->all();
        if (empty($payload)) {
            $payload = $request->all();
        }
        $normalized = $this->normalizePayload($payload);

        $validator = validator($normalized, [
            'student_id' => 'required|string|min:1|regex:/^\\d+$/',  // 接受字符串或数字类型，如"1764913638"或1764913638
            'teacher_id' => 'required|string|min:1|regex:/^\\d+$/',
            'paper_name' => 'nullable|string|max:255',
            'grade' => 'required|integer|in:7,8,9',
            'student_name' => 'required|string|max:50',
            'teacher_name' => 'required|string|max:50',
            'total_questions' => 'nullable|integer|min:1|max:100',
            'difficulty_category' => 'nullable|integer|in:1,2,3,4',
            'kp_codes' => 'nullable|array',
            'kp_codes.*' => 'string',
            'skills' => 'nullable|array',
            'skills.*' => 'string',
            'question_type_ratio' => 'nullable|array',
            // 'difficulty_ratio' 参数已废弃，使用 difficulty_category 控制难度分布
            'total_score' => 'nullable|numeric|min:1|max:1000',
            'mistake_ids' => 'nullable|array',
            'mistake_ids.*' => 'string',
            'mistake_question_ids' => 'nullable|array',
            'mistake_question_ids.*' => 'string',
            'callback_url' => 'nullable|url',  // 异步完成后推送通知的URL
            // 新增：组卷类型
            'assemble_type' => 'nullable|integer|in:0,1,2,3,4,5,6',
            'exam_type' => 'nullable|string|in:general,diagnostic,practice,mistake,textbook,knowledge,knowledge_points',
            // 错题本类型专用参数
            'paper_ids' => 'nullable|array',
            'paper_ids.*' => 'string',
            // 修改：使用series_id + semester_code + grade替代textbook_id
            'series_id' => 'nullable|integer|min:1',              // 教材系列ID（替代textbook_id）
            'semester_code' => 'nullable|integer|in:1,2',          // 上下册：1=上册，2=下册
            // 新增：各组卷类型的专用参数
            'chapter_id_list' => 'nullable|array',                // 教材组卷专用
            'chapter_id_list.*' => 'integer|min:1',
            'kp_code_list' => 'nullable|array',                   // 知识点组卷专用
            'kp_code_list.*' => 'string',
            // 新增：专项练习选项
            'practice_options' => 'nullable|array',
            'practice_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
            'practice_options.intensity' => 'nullable|string|in:low,medium,high',
            'practice_options.include_new_questions' => 'nullable|boolean',
            'practice_options.focus_weaknesses' => 'nullable|boolean',
            // 新增：错题选项
            'mistake_options' => 'nullable|array',
            'mistake_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
            'mistake_options.review_mistakes' => 'nullable|boolean',
            'mistake_options.intensity' => 'nullable|string|in:low,medium,high',
            'mistake_options.include_new_questions' => 'nullable|boolean',
            'mistake_options.focus_weaknesses' => 'nullable|boolean',
            // 新增：按知识点组卷选项
            'knowledge_points_options' => 'nullable|array',
            'knowledge_points_options.weakness_threshold' => 'nullable|numeric|min:0|max:1',
            'knowledge_points_options.intensity' => 'nullable|string|in:low,medium,high',
            'knowledge_points_options.focus_weaknesses' => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数错误',
                'errors' => $validator->errors()->toArray(),
            ], 422);
        }

        $data = $validator->validated();
        $data['total_questions'] = $data['total_questions'] ?? 20;
        $this->ensureStudentTeacherRelation($data);

        // 【修改】使用series_id、semester_code和grade获取textbook_id
        $textbookId = $this->resolveTextbookId($data);
        if ($textbookId) {
            $data['textbook_id'] = $textbookId;
        }

        // 确保 kp_codes 是数组
        $data['kp_codes'] = $data['kp_codes'] ?? [];
        if (!is_array($data['kp_codes'])) {
            $data['kp_codes'] = [];
        }

        $questionTypeRatio = $this->normalizeQuestionTypeRatio($data['question_type_ratio'] ?? []);
        // 注意: difficulty_ratio 参数已废弃，使用 difficulty_category 控制难度分布
        $paperName = $data['paper_name'] ?? ('智能试卷_' . now()->format('Ymd_His'));
        $difficultyCategory = $data['difficulty_category'] ?? 1; // 直接使用数字，不转换
        $mistakeIds = $data['mistake_ids'] ?? [];
        $mistakeQuestionIds = $data['mistake_question_ids'] ?? [];
        $paperIds = $data['paper_ids'] ?? [];
        $assembleType = $data['assemble_type'] ?? 4; // 默认为通用类型(4)

        try {
            $questions = [];
            $result = null;

            if (!empty($mistakeIds) || !empty($mistakeQuestionIds)) {
                $questionIds = $this->resolveMistakeQuestionIds(
                    $data['student_id'],
                    $mistakeIds,
                    $mistakeQuestionIds
                );

                if (empty($questionIds)) {
                    return response()->json([
                        'success' => false,
                        'message' => '未找到可用的错题题目，请检查错题ID或学生ID',
                    ], 400);
                }

                $bankQuestions = $this->questionBankService->getQuestionsByIds($questionIds)['data'] ?? [];
                if (empty($bankQuestions)) {
                    return response()->json([
                        'success' => false,
                        'message' => '错题对应的题库题目不存在或不可用',
                    ], 400);
                }

                $questions = $this->hydrateQuestions($bankQuestions, $data['kp_codes']);
                $questions = $this->sortQuestionsByRequestedIds($questions, $questionIds);
                $paperName = $data['paper_name'] ?? ('错题复习_' . $data['student_id'] . '_' . now()->format('Ymd_His'));
            } else {
                // 第一步：生成智能试卷（同步）
                $params = [
                    'student_id' => $data['student_id'],
                    'grade' => $data['grade'] ?? null,
                    'total_questions' => $data['total_questions'],
                    // 【修复】教材组卷时不使用用户传入的kp_codes，只使用章节关联的知识点
                    'kp_codes' => $assembleType == 3 ? null : ($data['kp_codes'] ?? null),
                    'kp_code_list' => $assembleType == 3 ? null : ($data['kp_code_list'] ?? $data['kp_codes'] ?? []),
                    'skills' => $data['skills'] ?? [],
                    'question_type_ratio' => $questionTypeRatio,
                    'difficulty_category' => $difficultyCategory, // 传递难度分类（数字）
                    'assemble_type' => $assembleType, // 新版组卷类型
                    'exam_type' => $data['exam_type'] ?? 'general', // 兼容旧版参数
                    'paper_ids' => $paperIds, // 错题本类型专用参数
                    'textbook_id' => $data['textbook_id'] ?? null, // 摸底和智能组卷专用
                    'chapter_id_list' => $data['chapter_id_list'] ?? null, // 教材组卷专用
                    'kp_code_list' => $assembleType == 3 ? null : ($data['kp_code_list'] ?? null), // 知识点组卷专用
                    'practice_options' => $data['practice_options'] ?? null, // 传递专项练习选项
                    'mistake_options' => $data['mistake_options'] ?? null, // 传递错题选项
                ];

                $result = $this->learningAnalyticsService->generateIntelligentExam($params);

                if (empty($result['success'])) {
                    $errorMsg = $result['message'] ?? '智能出卷失败';
                    Log::error('智能出卷失败', [
                        'student_id' => $data['student_id'],
                        'error' => $result
                    ]);

                    // 提供更详细的错误信息
                    if (strpos($errorMsg, '超时') !== false) {
                        $errorMsg = '服务响应超时，请稍后重试';
                    } elseif (strpos($errorMsg, '连接') !== false) {
                        $errorMsg = '依赖服务连接失败，请检查服务状态';
                    }

                    return response()->json([
                        'success' => false,
                        'message' => $errorMsg,
                        'details' => $result['details'] ?? null,
                    ], 400);
                }

                $questions = $this->hydrateQuestions($result['questions'] ?? [], $data['kp_codes']);
            }

            if (empty($questions)) {
                return response()->json([
                    'success' => false,
                    'message' => '未能生成有效题目，请检查知识点或题库数据',
                ], 400);
            }

            // 错题本类型不需要限制题目数量，由错题数量决定
            if ($assembleType === 5) {
                // 错题本：使用所有错题，不限制数量
                Log::info('错题本类型，使用所有错题', [
                    'assemble_type' => $assembleType,
                    'question_count' => count($questions)
                ]);
            } else {
                // 其他类型：限制题目数量
                $totalQuestions = min($data['total_questions'], count($questions));
                $questions = array_slice($questions, 0, $totalQuestions);
            }

            // 调整题目分值，确保符合中国中学卷子标准（总分100分）
            $questions = $this->adjustQuestionScores($questions, 100.0);

            // 计算总分
            $totalScore = array_sum(array_column($questions, 'score'));

            // 第二步：保存试卷到数据库（同步）
            $paperId = $this->questionBankService->saveExamToDatabase([
                'paper_name' => $paperName,
                'student_id' => $data['student_id'],
                'teacher_id' => $data['teacher_id'] ?? null,
                'difficulty_category' => $difficultyCategory,
                'total_score' => $data['total_score'] ?? 100.0, // 默认100分
                'questions' => $questions,
            ]);

            if (!$paperId) {
                return response()->json([
                    'success' => false,
                    'message' => '试卷保存失败',
                ], 500);
            }

            // 第三步：创建异步任务（使用TaskManager）
            // 注意：callback_url会在TaskManager中被提取并保存
            $taskId = $this->taskManager->createTask(TaskManager::TASK_TYPE_EXAM, array_merge($data, ['paper_id' => $paperId]));

            // 生成识别码
            $codes = $this->paperPayloadService->generatePaperCodes($paperId);

            // 立即返回完整的试卷数据（不等待PDF生成）
            $paperModel = Paper::with('questions')->find($paperId);
            $examContent = $paperModel
                ? $this->paperPayloadService->buildExamContent($paperModel)
                : [];

            // 触发后台PDF生成
            $this->triggerPdfGeneration($taskId, $paperId);

            $payload = [
                'success' => true,
                'message' => '智能试卷创建成功，PDF正在后台生成...',
                'data' => [
                    'task_id' => $taskId,
                    'paper_id' => $paperId,
                    'status' => 'processing',
                    // 识别码
                    'exam_code' => $codes['exam_code'],       // 试卷识别码 (1+12位)
                    'grading_code' => $codes['grading_code'], // 判卷识别码 (2+12位)
                    'paper_id_num' => $codes['paper_id_num'], // 12位数字ID
                    'exam_content' => $examContent,
                    'urls' => [
                        'grading_url' => route('filament.admin.auth.intelligent-exam.grading', ['paper_id' => $paperId]),
                        'student_exam_url' => route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']),
                    ],
                    'pdfs' => [
                        'exam_paper_pdf' => null,
                        'grading_pdf' => null,
                    ],
                    'stats' => $result['stats'] ?? [
                        'total_selected' => count($questions),
                        'mistake_based' => !empty($mistakeIds) || !empty($mistakeQuestionIds),
                    ],
                    'created_at' => now()->toISOString(),
                ],
            ];

            return response()->json($payload, 200, [], JSON_UNESCAPED_SLASHES);

        } catch (\Exception $e) {
            Log::error('Intelligent exam API failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            // 返回更具体的错误信息
            $errorMessage = $e->getMessage();
            if (strpos($errorMessage, 'Connection') !== false || strpos($errorMessage, 'connection') !== false) {
                $errorMessage = '依赖服务连接失败，请检查服务状态';
            } elseif (strpos($errorMessage, 'timeout') !== false || strpos($errorMessage, '超时') !== false) {
                $errorMessage = '服务响应超时，请稍后重试';
            } elseif (strpos($errorMessage, 'not found') !== false || strpos($errorMessage, '未找到') !== false) {
                $errorMessage = '请求的资源不存在';
            } elseif (strpos($errorMessage, 'invalid') !== false || strpos($errorMessage, '无效') !== false) {
                $errorMessage = '请求参数无效';
            }

            return response()->json([
                'success' => false,
                'message' => $errorMessage ?: '服务异常，请稍后重试',
            ], 500);
        }
    }

    /**
     * 轮询任务状态
     */
    public function status(string $taskId): JsonResponse
    {
        try {
            $task = $this->taskManager->getTaskStatus($taskId);

            if (!$task) {
                return response()->json([
                    'success' => false,
                    'message' => '任务不存在',
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $task,
            ]);

        } catch (\Exception $e) {
            Log::error('查询任务状态失败', [
                'task_id' => $taskId,
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'message' => '查询失败，请稍后重试',
            ], 500);
        }
    }

    /**
     * 触发PDF生成
     * 使用队列进行异步处理
     */
    private function triggerPdfGeneration(string $taskId, string $paperId): void
    {
        // 异步处理PDF生成 - 将任务放入队列
        try {
            dispatch(new \App\Jobs\GenerateExamPdfJob($taskId, $paperId));
            Log::info('PDF生成任务已加入队列', [
                'task_id' => $taskId,
                'paper_id' => $paperId
            ]);
        } catch (\Exception $e) {
            Log::error('PDF生成任务队列失败，不回退到同步处理', [
                'task_id' => $taskId,
                'paper_id' => $paperId,
                'error' => $e->getMessage(),
                'note' => '依赖队列重试机制，不进行同步处理以避免并发冲突'
            ]);
            // 【优化】不回退到同步处理，避免与队列任务并发冲突
            // 队列系统有重试机制，会自动处理失败情况
            // $this->processPdfGeneration($taskId, $paperId);
        }
    }

    /**
     * 处理PDF生成（模拟后台任务）
     * 在实际项目中，这个方法应该在队列worker中执行
     */
    private function processPdfGeneration(string $taskId, string $paperId): void
    {
        try {
            $this->taskManager->updateTaskProgress($taskId, 10, '开始生成试卷PDF...');

            // 生成试卷PDF
            $pdfUrl = $this->pdfExportService->generateExamPdf($paperId)
                ?? $this->questionBankService->exportExamToPdf($paperId)
                ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'false']);

            $this->taskManager->updateTaskProgress($taskId, 50, '试卷PDF生成完成，开始生成判卷PDF...');

            // 生成判卷PDF
            $gradingPdfUrl = $this->pdfExportService->generateGradingPdf($paperId)
                ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $paperId, 'answer' => 'true']);

            // 构建完整的试卷内容
            $paperModel = Paper::with('questions')->find($paperId);
            $examContent = $paperModel
                ? $this->paperPayloadService->buildExamContent($paperModel)
                : [];

            // 标记任务完成
            $this->taskManager->markTaskCompleted($taskId, [
                'exam_content' => $examContent,
                'pdfs' => [
                    'exam_paper_pdf' => $pdfUrl,
                    'grading_pdf' => $gradingPdfUrl,
                ],
            ]);

            Log::info('异步任务完成', [
                'task_id' => $taskId,
                'paper_id' => $paperId,
                'pdf_url' => $pdfUrl,
                'grading_pdf_url' => $gradingPdfUrl,
            ]);

            // 发送回调通知
            $this->taskManager->sendCallback($taskId);

        } catch (\Exception $e) {
            Log::error('PDF生成失败', [
                'task_id' => $taskId,
                'paper_id' => $paperId,
                'error' => $e->getMessage(),
            ]);

            $this->taskManager->markTaskFailed($taskId, $e->getMessage());
        }
    }

    /**
     * 兼容字符串/数组入参
     */
    private function normalizePayload(array $payload): array
    {
        // 处理 question_count 参数：转换为 total_questions
        if (isset($payload['question_count']) && !isset($payload['total_questions'])) {
            $payload['total_questions'] = $payload['question_count'];
            unset($payload['question_count']);
        }

        // 将student_id转换为字符串（支持数字和字符串输入）
        if (isset($payload['student_id'])) {
            $payload['student_id'] = (string) $payload['student_id'];
        }
        if (isset($payload['teacher_id'])) {
            $payload['teacher_id'] = (string) $payload['teacher_id'];
        }
        if (isset($payload['grade'])) {
            $payload['grade'] = (string) $payload['grade'];
        }

        // 处理 kp_codes：空字符串或null转换为空数组
        if (isset($payload['kp_codes'])) {
            if (is_string($payload['kp_codes'])) {
                $kpCodes = trim($payload['kp_codes']);
                if (empty($kpCodes)) {
                    $payload['kp_codes'] = [];
                } else {
                    $payload['kp_codes'] = array_values(array_filter(array_map('trim', explode(',', $kpCodes))));
                }
            } elseif (!is_array($payload['kp_codes'])) {
                $payload['kp_codes'] = [];
            }
        } else {
            $payload['kp_codes'] = [];
        }

        if (isset($payload['skills']) && is_string($payload['skills'])) {
            $payload['skills'] = array_values(array_filter(array_map('trim', explode(',', $payload['skills']))));
        }

        foreach (['mistake_ids', 'mistake_question_ids'] as $key) {
            if (isset($payload[$key])) {
                if (is_string($payload[$key])) {
                    $raw = trim($payload[$key]);
                    $payload[$key] = $raw === ''
                        ? []
                        : array_values(array_filter(array_map('trim', explode(',', $raw))));
                } elseif (!is_array($payload[$key])) {
                    $payload[$key] = [];
                }
            }
        }

        // 新增：处理组卷专用参数
        foreach (['chapter_id_list', 'kp_code_list'] as $key) {
            if (isset($payload[$key])) {
                if (is_string($payload[$key])) {
                    $raw = trim($payload[$key]);
                    $payload[$key] = $raw === ''
                        ? []
                        : array_values(array_filter(array_map('trim', explode(',', $raw))));
                } elseif (!is_array($payload[$key])) {
                    $payload[$key] = [];
                }
            } else {
                $payload[$key] = [];
            }
        }

        // 【修改】处理series_id：字符串转换为整数
        if (isset($payload['series_id'])) {
            if (is_string($payload['series_id'])) {
                $payload['series_id'] = (int) trim($payload['series_id']);
                if ($payload['series_id'] <= 0) {
                    unset($payload['series_id']);
                }
            } elseif (!is_int($payload['series_id']) || $payload['series_id'] <= 0) {
                unset($payload['series_id']);
            }
        }

        // 【新增】处理semester_code：确保是1或2
        if (isset($payload['semester_code'])) {
            if (is_string($payload['semester_code'])) {
                $payload['semester_code'] = (int) trim($payload['semester_code']);
            }
            // 只保留1或2，其他值都移除
            if (!in_array($payload['semester_code'], [1, 2], true)) {
                unset($payload['semester_code']);
            }
        }

        // 新增：处理组卷类型，默认值为 general
        if (!isset($payload['exam_type'])) {
            $payload['exam_type'] = 'general';
        }

        // 新增：处理专项练习选项
        if (isset($payload['practice_options'])) {
            if (is_string($payload['practice_options'])) {
                $decoded = json_decode($payload['practice_options'], true);
                $payload['practice_options'] = is_array($decoded) ? $decoded : [];
            } elseif (!is_array($payload['practice_options'])) {
                $payload['practice_options'] = [];
            }

            // 设置默认值
            $payload['practice_options'] = array_merge([
                'weakness_threshold' => 0.7,
                'intensity' => 'medium',
                'include_new_questions' => true,
                'focus_weaknesses' => true,
            ], $payload['practice_options']);
        } else {
            // 如果没有提供 practice_options，创建默认值
            $payload['practice_options'] = [
                'weakness_threshold' => 0.7,
                'intensity' => 'medium',
                'include_new_questions' => true,
                'focus_weaknesses' => true,
            ];
        }

        // 新增：处理错题选项
        if (isset($payload['mistake_options'])) {
            if (is_string($payload['mistake_options'])) {
                $decoded = json_decode($payload['mistake_options'], true);
                $payload['mistake_options'] = is_array($decoded) ? $decoded : [];
            } elseif (!is_array($payload['mistake_options'])) {
                $payload['mistake_options'] = [];
            }

            // 设置默认值
            $payload['mistake_options'] = array_merge([
                'weakness_threshold' => 0.7,
                'review_mistakes' => true,
                'intensity' => 'medium',
                'include_new_questions' => true,
                'focus_weaknesses' => true,
            ], $payload['mistake_options']);
        } else {
            // 如果没有提供 mistake_options，创建默认值
            $payload['mistake_options'] = [
                'weakness_threshold' => 0.7,
                'review_mistakes' => true,
                'intensity' => 'medium',
                'include_new_questions' => true,
                'focus_weaknesses' => true,
            ];
        }

        // 新增：处理按知识点组卷选项
        if (isset($payload['knowledge_points_options'])) {
            if (is_string($payload['knowledge_points_options'])) {
                $decoded = json_decode($payload['knowledge_points_options'], true);
                $payload['knowledge_points_options'] = is_array($decoded) ? $decoded : [];
            } elseif (!is_array($payload['knowledge_points_options'])) {
                $payload['knowledge_points_options'] = [];
            }

            // 设置默认值
            $payload['knowledge_points_options'] = array_merge([
                'weakness_threshold' => 0.7,
                'intensity' => 'medium',
                'focus_weaknesses' => true,
            ], $payload['knowledge_points_options']);
        } else {
            // 如果没有提供 knowledge_points_options，创建默认值
            $payload['knowledge_points_options'] = [
                'weakness_threshold' => 0.7,
                'intensity' => 'medium',
                'focus_weaknesses' => true,
            ];
        }

        return $payload;
    }

    private function ensureStudentTeacherRelation(array $data): void
    {
        $studentId = (int) $data['student_id'];
        $teacherId = (int) $data['teacher_id'];
        $studentName = (string) ($data['student_name'] ?? '未知学生');
        $teacherName = (string) ($data['teacher_name'] ?? '未知教师');
        $grade = (string) ($data['grade'] ?? '未知年级');

        $teacher = $this->externalIdService->handleTeacherExternalId($teacherId, [
            'name' => $teacherName,
            'subject' => '数学',
        ]);

        $student = Student::where('student_id', $studentId)->first();
        if ($student) {
            $updates = [];
            if ($studentName !== '' && $student->name !== $studentName) {
                $updates['name'] = $studentName;
            }
            if ($grade !== '' && $student->grade !== $grade) {
                $updates['grade'] = $grade;
            }
            if ($teacherId > 0 && (int) $student->teacher_id !== $teacherId) {
                $updates['teacher_id'] = $teacherId;
            }
            if (!empty($updates)) {
                $student->update($updates);
            }
            return;
        }

        $this->externalIdService->handleStudentExternalId($studentId, [
            'name' => $studentName,
            'grade' => $grade,
            'teacher_id' => $teacherId,
        ]);
    }

    private function normalizeQuestionTypeRatio(array $input): array
    {
        // 默认按 4:2:4
        $defaults = [
            '选择题' => 40,
            '填空题' => 20,
            '解答题' => 40,
        ];

        $normalized = [];
        foreach ($input as $key => $value) {
            if (!is_numeric($value)) {
                continue;
            }
            $type = $this->normalizeQuestionTypeKey($key);
            if ($type) {
                $normalized[$type] = (float) $value;
            }
        }

        $merged = array_merge($defaults, $normalized);

        // 归一化到 100%
        $sum = array_sum($merged);
        if ($sum > 0) {
            foreach ($merged as $k => $v) {
                $merged[$k] = round(($v / $sum) * 100, 2);
            }
        }

        return $merged;
    }

    private function normalizeQuestionTypeKey(string $key): ?string
    {
        $key = trim($key);
        if (in_array($key, ['choice', '选择题', 'single_choice', 'multiple_choice', 'CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
            return '选择题';
        }
        if (in_array($key, ['fill', '填空题', 'blank', 'FILL_IN_THE_BLANK', 'FILL'], true)) {
            return '填空题';
        }
        if (in_array($key, ['answer', '解答题', '计算题', 'CALCULATION', 'WORD_PROBLEM', 'PROOF'], true)) {
            return '解答题';
        }

        return null;
    }

    private function normalizeDifficultyRatio(array $input): array
    {
        $defaults = [
            '基础' => 50,
            '中等' => 35,
            '拔高' => 15,
        ];

        $normalized = [];
        foreach ($input as $key => $value) {
            if (!is_numeric($value)) {
                continue;
            }
            $label = trim($key);
            if (in_array($label, ['基础', 'easy', '简单'])) {
                $normalized['基础'] = (float) $value;
            } elseif (in_array($label, ['中等', 'medium'])) {
                $normalized['中等'] = (float) $value;
            } elseif (in_array($label, ['拔高', 'hard', '困难', '竞赛'])) {
                $normalized['拔高'] = (float) $value;
            }
        }

        return array_merge($defaults, $normalized);
    }

    private function hydrateQuestions(array $questions, array $kpCodes): array
    {
        $normalized = [];
        foreach ($questions as $question) {
            $type = $this->normalizeQuestionTypeKey($question['question_type'] ?? $question['type'] ?? '') ?? $this->guessType($question);
            $score = $question['score'] ?? $this->defaultScore($type);

            $normalized[] = [
                'id' => $question['id'] ?? $question['question_id'] ?? null,
                'question_id' => $question['question_id'] ?? null,
                'question_type' => $type === '选择题' ? 'choice' : ($type === '填空题' ? 'fill' : 'answer'),
                'stem' => $question['stem'] ?? $question['content'] ?? ($question['question_text'] ?? ''),
                'content' => $question['content'] ?? $question['stem'] ?? '',
                'options' => $question['options'] ?? ($question['choices'] ?? []),
                'answer' => $question['answer'] ?? $question['correct_answer'] ?? '',
                'solution' => $question['solution'] ?? '',
                'difficulty' => isset($question['difficulty']) ? (float) $question['difficulty'] : 0.5,
                'score' => $score,
                'estimated_time' => $question['estimated_time'] ?? 300,
                'kp' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
                'kp_code' => $question['kp_code'] ?? $question['kp'] ?? $question['knowledge_point'] ?? ($kpCodes[0] ?? ''),
            ];
        }

        return array_values(array_filter($normalized, fn ($q) => !empty($q['id'])));
    }

    private function guessType(array $question): string
    {
        if (!empty($question['options']) && is_array($question['options'])) {
            return '选择题';
        }

        $content = $question['stem'] ?? $question['content'] ?? '';
        if (is_string($content) && (strpos($content, '____') !== false || strpos($content, '（）') !== false)) {
            return '填空题';
        }

        return '解答题';
    }

    /**
     * 根据题目类型获取默认分值（中国中学卷子标准）
     * 选择题：5分/题，填空题：5分/题，解答题：10分/题
     */
    private function defaultScore(string $type): int
    {
        return match ($type) {
            '选择题' => 5,
            '填空题' => 5,
            '解答题' => 10,
            default => 5,
        };
    }

    /**
     * 计算试卷总分并调整各题目分值，确保总分接近目标分数
     * 符合中国中学卷子标准：
     * - 选择题：约40%总分（每题4-6分，整数分值）
     * - 填空题：约25%总分（每题4-6分，整数分值）
     * - 解答题：约35%总分（每题8-12分，整数分值）
     * 使用组合优化算法确保：
     * 1. 所有分值都是整数（无小数点）
     * 2. 同类型题目分值均匀
     * 3. 总分精确匹配目标分数（或最接近）
     */
    private function adjustQuestionScores(array $questions, float $targetTotalScore = 100.0): array
    {
        if (empty($questions)) {
            return $questions;
        }

        // 统计各类型题目数量
        $typeCounts = ['choice' => 0, 'fill' => 0, 'answer' => 0];

        foreach ($questions as $question) {
            $type = $question['question_type'] ?? 'answer';
            if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
                $type = 'choice';
            } elseif (in_array($type, ['FILL_IN_THE_BLANK', 'FILL'], true)) {
                $type = 'fill';
            } elseif (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF', 'ANSWER'], true)) {
                $type = 'answer';
            }
            if (isset($typeCounts[$type])) {
                $typeCounts[$type]++;
            }
        }

        // 标准分值范围
        $standardScoreRanges = [
            'choice' => ['min' => 4, 'max' => 6],
            'fill' => ['min' => 4, 'max' => 6],
            'answer' => ['min' => 8, 'max' => 12],
        ];

        // 目标比例
        $typeRatios = ['choice' => 0.40, 'fill' => 0.25, 'answer' => 0.35];

        // 检查可用题型
        $availableTypes = array_filter($typeCounts, fn($count) => $count > 0);
        $availableTypeCount = count($availableTypes);
        $isPartialTypes = $availableTypeCount < 3 && $availableTypeCount > 0;

        if ($isPartialTypes) {
            $equalRatio = 1.0 / $availableTypeCount;
            foreach ($typeCounts as $type => $count) {
                if ($count > 0) {
                    $typeRatios[$type] = $equalRatio;
                } else {
                    $typeRatios[$type] = 0;
                }
            }
        }

        $typeQuestionIndexes = ['choice' => [], 'fill' => [], 'answer' => []];

        // 记录每种题型的题目索引
        foreach ($questions as $index => $question) {
            $type = $question['question_type'] ?? 'answer';
            if (in_array($type, ['CHOICE', 'SINGLE_CHOICE', 'MULTIPLE_CHOICE'], true)) {
                $type = 'choice';
            } elseif (in_array($type, ['FILL_IN_THE_BLANK', 'FILL'], true)) {
                $type = 'fill';
            } elseif (in_array($type, ['CALCULATION', 'WORD_PROBLEM', 'PROOF', 'ANSWER'], true)) {
                $type = 'answer';
            }
            $typeQuestionIndexes[$type][] = $index;
        }

        // 生成每种题型的可能分值选项
        $typeScoreOptions = [];
        foreach ($typeQuestionIndexes as $type => $indexes) {
            if (empty($indexes)) {
                continue;
            }

            $typeQuestionCount = count($indexes);
            $minScore = $standardScoreRanges[$type]['min'];
            $maxScore = $standardScoreRanges[$type]['max'];
            $targetTotal = $targetTotalScore * $typeRatios[$type];
            $idealPerQuestion = $targetTotal / $typeQuestionCount;

            $options = [];

            // 添加标准范围内的选项
            for ($score = $minScore; $score <= $maxScore; $score++) {
                $total = $score * $typeQuestionCount;
                $options[] = [
                    'score' => $score,
                    'total' => $total,
                    'difference' => abs($targetTotalScore - $total),
                ];
            }

            // 如果是部分题型，大幅扩展搜索范围
            if ($isPartialTypes) {
                $idealScore = (int) round($idealPerQuestion);
                $searchMin = max($minScore, $idealScore - 10);
                $searchMax = $idealScore + 10;

                for ($score = $searchMin; $score <= $searchMax; $score++) {
                    if ($score >= $minScore) {
                        $total = $score * $typeQuestionCount;
                        if (!in_array($total, array_column($options, 'total'))) {
                            $options[] = [
                                'score' => $score,
                                'total' => $total,
                                'difference' => abs($targetTotalScore - $total),
                            ];
                        }
                    }
                }
            }

            $typeScoreOptions[$type] = $options;
        }

        // 生成所有可能的组合
        $types = array_keys(array_filter($typeQuestionIndexes, fn($indexes) => !empty($indexes)));
        $allCombinations = [[]];

        foreach ($types as $type) {
            $newCombinations = [];
            foreach ($allCombinations as $combo) {
                foreach ($typeScoreOptions[$type] as $option) {
                    $newCombo = $combo;
                    $newCombo[$type] = $option;
                    $newCombinations[] = $newCombo;
                }
            }
            $allCombinations = $newCombinations;
        }

        // 找到最佳组合（优先精确匹配，其次最接近）
        $bestCombination = null;
        $bestDifference = PHP_FLOAT_MAX;
        $exactMatchFound = false;

        foreach ($allCombinations as $combo) {
            $totalScore = array_sum(array_column($combo, 'total'));
            $difference = abs($targetTotalScore - $totalScore);

            if ($difference == 0) {
                $bestCombination = $combo;
                $exactMatchFound = true;
                break;
            }

            if ($difference < $bestDifference) {
                $bestDifference = $difference;
                $bestCombination = $combo;
            }
        }

        // 应用最佳组合
        $adjustedQuestions = [];
        if ($bestCombination) {
            foreach ($bestCombination as $type => $option) {
                $score = $option['score'];
                foreach ($typeQuestionIndexes[$type] as $index) {
                    $question = $questions[$index];
                    $question['score'] = $score;
                    $adjustedQuestions[$index] = $question;
                }
            }
        }

        return array_values($adjustedQuestions);
    }

    private function resolveMistakeQuestionIds(string $studentId, array $mistakeIds, array $mistakeQuestionIds): array
    {
        $questionIds = [];

        if (!empty($mistakeQuestionIds)) {
            $questionIds = array_merge($questionIds, $mistakeQuestionIds);
        }

        if (!empty($mistakeIds)) {
            $mistakeQuestionIdsFromDb = MistakeRecord::query()
                ->where('student_id', $studentId)
                ->whereIn('id', $mistakeIds)
                ->pluck('question_id')
                ->filter()
                ->values()
                ->all();

            $questionIds = array_merge($questionIds, $mistakeQuestionIdsFromDb);
        }

        $questionIds = array_values(array_unique(array_filter($questionIds)));
        return $questionIds;
    }

    private function sortQuestionsByRequestedIds(array $questions, array $requestedIds): array
    {
        if (empty($requestedIds)) {
            return $questions;
        }

        $order = array_flip($requestedIds);
        usort($questions, function ($a, $b) use ($order) {
            $aId = (string) ($a['id'] ?? '');
            $bId = (string) ($b['id'] ?? '');
            $aPos = $order[$aId] ?? PHP_INT_MAX;
            $bPos = $order[$bId] ?? PHP_INT_MAX;
            return $aPos <=> $bPos;
        });

        return $questions;
    }

    /**
     * 【新增】根据series_id、semester_code和grade获取textbook_id
     * 替代原来直接传入textbook_id的方式
     */
    private function resolveTextbookId(array $data): ?int
    {
        // 如果提供了series_id和semester_code，则查询textbook_id
        $seriesId = $data['series_id'] ?? null;
        $semesterCode = $data['semester_code'] ?? null;
        $grade = $data['grade'] ?? null;

        // 如果没有提供series_id或semester_code，则不设置textbook_id
        if (!$seriesId || !$semesterCode) {
            return null;
        }

        try {
            // 根据series_id、semester_code和grade查询textbooks表
            $query = DB::connection('mysql')
                ->table('textbooks')
                ->where('series_id', $seriesId)
                ->where('semester', $semesterCode);

            // 如果提供了grade，可以作为额外筛选条件
            if ($grade) {
                $query->where('grade', $grade);
            }

            $textbook = $query->first();

            if ($textbook) {
                Log::info('成功解析textbook_id', [
                    'series_id' => $seriesId,
                    'semester_code' => $semesterCode,
                    'grade' => $grade,
                    'textbook_id' => $textbook->id
                ]);
                return (int) $textbook->id;
            }

            Log::warning('未找到匹配的教材', [
                'series_id' => $seriesId,
                'semester_code' => $semesterCode,
                'grade' => $grade
            ]);
            return null;

        } catch (\Exception $e) {
            Log::error('查询textbook_id失败', [
                'series_id' => $seriesId,
                'semester_code' => $semesterCode,
                'grade' => $grade,
                'error' => $e->getMessage()
            ]);
            return null;
        }
    }
}
