<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use App\Models\StudentKnowledgeMastery;
use App\Models\MistakeRecord;
use App\Models\KnowledgePoint;
use App\Models\Paper;
use App\Models\PaperQuestion;
use App\Models\Question;
use Illuminate\Support\Facades\DB;

class ExamTypeStrategy
{
    protected QuestionExpansionService $questionExpansionService;
    protected QuestionLocalService $questionLocalService;
    protected DifficultyDistributionService $difficultyDistributionService;

    public function __construct(
        QuestionExpansionService $questionExpansionService,
        QuestionLocalService $questionLocalService = null,
        DifficultyDistributionService $difficultyDistributionService = null
    )
    {
        $this->questionExpansionService = $questionExpansionService;
        $this->questionLocalService = $questionLocalService ?? app(QuestionLocalService::class);
        $this->difficultyDistributionService = $difficultyDistributionService ?? app(DifficultyDistributionService::class);
    }

    private static function defaultTotalQuestions(): int
    {
        return (int) config('question_bank.default_total_questions');
    }

    /**
     * 根据组卷类型构建参数
     * assembleType: 0-章节摸底, 1-智能组卷, 2-知识点组卷, 3-教材组卷, 4-通用, 5-按卷追练(paper_ids=试卷), 8-智能组卷(新), 9-原摸底, 15-错题再练(paper_ids=题库题目id，由 AssembleExamTaskJob 单独处理)
     *
     * 映射规则（前端不改，后端动态处理）：
     * - 0, 9（摸底）→ 章节摸底（新逻辑）
     * - 1, 8（智能组卷）→ 按知识点顺序学习（新逻辑）
     * - 2, 3, 4, 5 → 保持原有逻辑不变（5 的 paper_ids 为试卷 ID；15 不入此策略，由 AssembleExamTaskJob 直组）
     */
    public function buildParams(array $baseParams, int $assembleType): array
    {
        // 映射 assembleType 到实际处理逻辑
        $actualType = match($assembleType) {
            0, 9 => 'chapter_diagnostic',   // 摸底 → 章节摸底（新逻辑）
            1, 8 => 'chapter_intelligent',  // 智能组卷 → 按知识点顺序学习（新逻辑）
            default => $assembleType        // 其他保持不变
        };

        Log::debug('ExamTypeStrategy: 构建组卷参数', [
            'assemble_type' => $assembleType,
            'actual_type' => $actualType,
        ]);

        return match($actualType) {
            'chapter_diagnostic' => $this->applyDifficultyDistribution($this->buildChapterDiagnosticParams($baseParams)), // 章节摸底（新）
            'chapter_intelligent' => $this->applyDifficultyDistribution($this->buildChapterIntelligentParams($baseParams)), // 按知识点顺序学习（新）
            2 => $this->applyDifficultyDistribution($this->buildKnowledgePointAssembleParams($baseParams)), // 知识点组卷（不动）
            3 => $this->applyDifficultyDistribution($this->buildTextbookAssembleParams($baseParams)), // 教材组卷（不动）
            4 => $this->applyDifficultyDistribution($this->buildGeneralParams($baseParams)), // 通用（不动）
            5 => $this->applyDifficultyDistribution($this->buildMistakeParams($baseParams)), // 追练（不动）
            default => $this->applyDifficultyDistribution($this->buildGeneralParams($baseParams))
        };
    }

    /**
     * 根据组卷类型构建参数（兼容旧版 exam_type 参数）
     * @deprecated 使用 buildParams(array, int) 替代
     */
    public function buildParamsLegacy(array $baseParams, string $examType): array
    {
        // 兼容旧版 exam_type 参数
        $assembleType = match($examType) {
            'diagnostic' => 9,
            'general' => 4,
            'practice' => 5,
            'mistake' => 5,
            'textbook' => 3,
            'knowledge' => 2,
            'knowledge_points' => 6,
            default => 4
        };

        return $this->buildParams($baseParams, $assembleType);
    }

    /**
     * 通用智能出卷（原有行为）
     */
    private function buildGeneralParams(array $params): array
    {
        Log::debug('ExamTypeStrategy: 通用智能出卷参数', array_keys($params));

        // 返回原始参数，难度分布逻辑在 buildParams 中统一处理
        return $params;
    }

    /**
     * 应用难度系数分布逻辑
     * 根据 difficulty_category 参数实现分层选题策略
     *
     * @param array $params 基础参数
     * @param bool $forceApply 是否强制应用（默认false，不对错题本类型应用）
     * @return array 增强后的参数
     */
    private function applyDifficultyDistribution(array $params, bool $forceApply = false): array
    {
        // 统一应用难度分布（错题本类型也允许应用）
        $assembleType = (int) ($params['assemble_type'] ?? 4);

        $difficultyCategory = (int) ($params['difficulty_category'] ?? 1);
        $totalQuestions = (int) ($params['total_questions'] ?? self::defaultTotalQuestions());

        Log::debug('ExamTypeStrategy: 应用难度系数分布', [
            'difficulty_category' => $difficultyCategory,
            'total_questions' => $totalQuestions
        ]);

        // 根据难度类别计算题目分布
        $distribution = $this->difficultyDistributionService->calculateDistribution($difficultyCategory, $totalQuestions);

        // 构建难度分布配置
        $difficultyDistributionConfig = [
            'strategy' => 'difficulty分层选题',
            'category' => $difficultyCategory,
            'total_questions' => $totalQuestions,
            'distribution' => $distribution,
            'ranges' => $this->difficultyDistributionService->getRanges($difficultyCategory),
            'use_question_local_service' => true, // 标记使用新的独立方法
        ];

        $enhanced = array_merge($params, [
            'difficulty_distribution_config' => $difficultyDistributionConfig,
            // 保留原有的 difficulty_ratio 以兼容性
            'difficulty_ratio' => [
                '基础' => $distribution['low']['percentage'],
                '中等' => $distribution['medium']['percentage'],
                '拔高' => $distribution['high']['percentage'],
            ],
            // 启用难度分布选题标志
            'enable_difficulty_distribution' => true,
            // 【重要】保持原始的 difficulty_category，不修改
            'difficulty_category' => $difficultyCategory,
        ]);

        Log::debug('ExamTypeStrategy: 难度分布应用完成', [
            'category' => $difficultyCategory,
            'distribution' => $distribution
        ]);

        return $enhanced;
    }

    /**
     * 应用难度分布到题目集合
     * 这是一个独立的公共方法，供外部调用
     *
     * @param array $questions 候选题目数组
     * @param int $totalQuestions 总题目数
     * @param int $difficultyCategory 难度类别 (1-4)
     * @param array $filters 其他筛选条件
     * @return array 分布后的题目
     */
    public function applyDifficultyDistributionToQuestions(array $questions, int $totalQuestions, int $difficultyCategory = 1, array $filters = []): array
    {
        Log::info('ExamTypeStrategy: 应用难度分布到题目集合', [
            'total_questions' => $totalQuestions,
            'difficulty_category' => $difficultyCategory,
            'input_questions' => count($questions)
        ]);

        // 使用 QuestionLocalService 的独立方法
        return $this->questionLocalService->selectQuestionsByDifficultyDistribution(
            $questions,
            $totalQuestions,
            $difficultyCategory,
            $filters
        );
    }

    /**
     * 根据难度类别计算题目分布
     *
     * @param int $category 难度类别 (0-4)
     * @param int $totalQuestions 总题目数
     * @return array 分布配置
     */
    private function calculateDifficultyDistribution(int $category, int $totalQuestions): array
    {
        return $this->difficultyDistributionService->calculateDistribution($category, $totalQuestions);
    }

    /**
     * 获取难度范围配置
     *
     * @param int $category 难度类别
     * @return array 难度范围配置
     */
    private function getDifficultyRanges(int $category): array
    {
        return $this->difficultyDistributionService->getRanges($category);
    }

    /**
     * 摸底测试：评估当前水平
     */
    private function buildDiagnosticParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建摸底测试参数', $params);

        $textbookId = $params['textbook_id'] ?? null;
        $grade = $params['grade'] ?? null;
        $totalQuestions = $params['total_questions'] ?? self::defaultTotalQuestions();
        $endCatalogId = $params['end_catalog_id'] ?? null; // 截止章节ID

        if (!$textbookId) {
            Log::warning('ExamTypeStrategy: 摸底测试需要 textbook_id 参数');
            return $this->buildGeneralParams($params);
        }

        // 第一步：根据 textbook_id 查询章节（支持截止章节过滤）
        $catalogChapterIds = $this->getTextbookChapterIds($textbookId, $endCatalogId);

        if (empty($catalogChapterIds)) {
            Log::warning('ExamTypeStrategy: 未找到课本章节', ['textbook_id' => $textbookId]);
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 获取到课本章节（摸底测试）', [
            'textbook_id' => $textbookId,
            'end_catalog_id' => $endCatalogId,
            'chapter_count' => count($catalogChapterIds)
        ]);

        // 第二步：根据章节ID查询知识点关联
        $kpCodes = $this->getKnowledgePointsFromChapters($catalogChapterIds, 25);

        if (empty($kpCodes)) {
            Log::warning('ExamTypeStrategy: 未找到知识点关联', ['textbook_id' => $textbookId]);
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 获取到知识点（摸底测试）', [
            'kp_count' => count($kpCodes),
            'kp_codes' => $kpCodes,
            'textbook_id' => $textbookId,
            'grade' => $grade,
            'note' => '知识点数量将直接影响题目多样性'
        ]);

        // 摸底测试：平衡所有难度，覆盖多个知识点
        // 【修复】移除硬编码难度配比，使用difficulty_category参数动态计算
        $enhanced = array_merge($params, [
            'kp_codes' => $kpCodes,
            'textbook_id' => $textbookId,
            'grade' => $grade,
            'catalog_chapter_ids' => $catalogChapterIds,
            // 题型配比：选择题多一些，便于快速评估
            'question_type_ratio' => [
                '选择题' => 50,
                '填空题' => 25,
                '解答题' => 25,
            ],
            'paper_name' => $params['paper_name'] ?? ('摸底测试_' . now()->format('Ymd_His')),
        ]);

        Log::info('ExamTypeStrategy: 摸底测试参数构建完成（未应用难度分布）', [
            'textbook_id' => $textbookId,
            'kp_count' => count($kpCodes),
            'total_questions' => $totalQuestions,
            'difficulty_category' => $params['difficulty_category'] ?? 1,
            'note' => '将在buildParams中应用difficulty_category难度分布'
        ]);

        return $enhanced;
    }

    /**
     * 新摸底测试：使用教材首章知识点作为起点，复用知识点组卷逻辑
     */
    private function buildInitialDiagnosticParams(array $params): array
    {
//        Log::info('ExamTypeStrategy: 构建新摸底测试参数', $params);

        $diagnosticService = app(DiagnosticChapterService::class);
        $textbookId = $params['textbook_id'] ?? null;
        $grade = $params['grade'] ?? null;
        $totalQuestions = $params['total_questions'] ?? self::defaultTotalQuestions();

        Log::info('ExamTypeStrategy: 新摸底使用textbook_id', [
            'textbook_id' => $textbookId,
        ]);

        if (!$textbookId) {
            Log::warning('ExamTypeStrategy: 新摸底测试需要 textbook_id 参数');
            return $this->buildGeneralParams($params);
        }

        $studentId = (int) ($params['student_id'] ?? 0);
        $initial = $diagnosticService->getFirstUnmasteredChapterKnowledgePoints((int) $textbookId, $studentId, 0.9);
        if (empty($initial)) {
            $initial = $diagnosticService->getInitialChapterKnowledgePoints((int) $textbookId);
        }

        if (empty($initial['kp_codes'])) {
            Log::warning('ExamTypeStrategy: 新摸底未找到首章知识点', [
                'textbook_id' => $textbookId,
            ]);
            return $this->buildGeneralParams($params);
        }

        $enhanced = array_merge($params, [
            'kp_code_list' => $initial['kp_codes'],
            'chapter_id_list' => $initial['section_ids'],
            'diagnostic_chapter_id' => $initial['chapter_id'],
            'textbook_id' => $textbookId,
            'grade' => $grade,
            'paper_name' => $params['paper_name'] ?? ('摸底测试_' . now()->format('Ymd_His')),
        ]);

        Log::info('ExamTypeStrategy: 新摸底参数构建完成', [
            'textbook_id' => $textbookId,
            'chapter_id' => $initial['chapter_id'] ?? null,
            'section_count' => count($initial['section_ids'] ?? []),
            'kp_count' => count($initial['kp_codes'] ?? []),
            'total_questions' => $totalQuestions,
        ]);

        return $this->buildKnowledgePointAssembleParams($enhanced);
    }

    /**
     * 追练 (assembleType=5)
     * 根据 paper_ids 获取卷子题目知识点列表，再按知识点组卷
     * 不需要 total_questions 参数
     */
    private function buildMistakeParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建追练参数', $params);

        $paperIds = $params['paper_ids'] ?? [];
        $studentId = $params['student_id'] ?? null;

        // 检查是否有 paper_ids 参数
        if (empty($paperIds)) {
            Log::warning('ExamTypeStrategy: 追练需要 paper_ids 参数');
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 追练组卷', [
            'paper_ids' => $paperIds,
            'student_id' => $studentId,
            'paper_count' => count($paperIds)
        ]);

        // 通过 paper_ids 查询卷子中的全部题目
        $paperQuestionIds = $this->getQuestionIdsFromPapers($paperIds);

        if (empty($paperQuestionIds)) {
            Log::warning('ExamTypeStrategy: 卷子题目为空，无法生成追练', [
                'paper_ids' => $paperIds
            ]);
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 获取到卷子题目', [
            'paper_count' => count($paperIds),
            'question_count' => count($paperQuestionIds),
            'question_ids' => array_slice($paperQuestionIds, 0, 10) // 只记录前10个
        ]);

        // 优先从错题记录获取知识点；若无错题则回退到卷子题目知识点
        $paperKnowledgePoints = $this->getMistakeKnowledgePointsFromPapers($studentId, $paperIds);
        $useMistakeKnowledgePoints = ! empty($paperKnowledgePoints);
        if (! $useMistakeKnowledgePoints) {
            // 获取卷子题目知识点（直接从 paper_questions.knowledge_point）
            $paperKnowledgePoints = $this->getKnowledgePointsFromPaperQuestions($paperIds);
        }

        // 排除错题本已有题目，避免重复出现
        $excludeQuestionIds = $this->getMistakeQuestionIdsFromPapers($studentId, $paperIds);

        Log::info('ExamTypeStrategy: 追练知识点来源', [
            'student_id' => $studentId,
            'paper_ids' => $paperIds,
            'use_mistake_kp' => $useMistakeKnowledgePoints,
            'kp_count' => count($paperKnowledgePoints),
            'exclude_count' => count($excludeQuestionIds),
        ]);

        if (empty($paperKnowledgePoints)) {
            Log::warning('ExamTypeStrategy: 卷子题目未找到知识点，无法生成错题本', [
                'paper_ids' => $paperIds,
                'question_count' => count($paperQuestionIds)
            ]);
            return $this->buildGeneralParams($params);
        }

        // 取卷子中最小难度等级、最大题量与最高总分作为默认
        $paperStats = $this->getPaperAggregateStats($paperIds);
        $difficultyCategory = $paperStats['difficulty_category_min'] ?? ($params['difficulty_category'] ?? 1);
        $maxTotalQuestions = $paperStats['total_questions_max'] ?? null;
        $maxTotalScore = $paperStats['total_score_max'] ?? null;

        // 组装增强参数（复用知识点组卷逻辑）
        $questionCount = count($paperQuestionIds);
        $maxQuestions = 50; // 源侧题量上限，避免一次拉过多
        if ($questionCount > $maxQuestions) {
            Log::warning('ExamTypeStrategy: 错题数量超过最大值限制，已截取', [
                'question_count' => $questionCount,
                'max_limit' => $maxQuestions,
                'truncated_count' => $maxQuestions
            ]);
            $questionCount = $maxQuestions;
        }

        $requested = (int) ($params['total_questions'] ?? self::defaultTotalQuestions());
        $fromPaper = (int) ($maxTotalQuestions ?? $questionCount);
        $targetQuestions = min($requested, $fromPaper, $maxQuestions);

        $enhanced = array_merge($params, [
            'kp_code_list' => array_values($paperKnowledgePoints),
            'paper_ids' => $paperIds,
            'paper_name' => $params['paper_name'] ?? ('追练_' . now()->format('Ymd_His')),
            'total_questions' => $targetQuestions, // 与 API/默认题量对齐，不超过源卷子可支撑题量
            'total_score' => $maxTotalScore ?? ($params['total_score'] ?? null),
            'difficulty_category' => $difficultyCategory,
            'is_mistake_exam' => true,
            'is_paper_based_mistake' => true, // 标记是基于卷子的错题本
            'mistake_kp_source' => $useMistakeKnowledgePoints,
            'exclude_question_ids' => $excludeQuestionIds,
            'source_paper_question_count' => $questionCount,
            'knowledge_points_count' => count($paperKnowledgePoints),
            'max_questions_limit' => $maxQuestions,
        ]);

        Log::info('ExamTypeStrategy: 错题本参数构建完成（按卷子知识点）', [
            'paper_count' => count($paperIds),
            'question_count' => $questionCount,
            'knowledge_points_count' => count($paperKnowledgePoints),
            'total_questions' => $targetQuestions,
            'difficulty_category' => $difficultyCategory,
            'total_score' => $maxTotalScore
        ]);

        Log::debug('ExamTypeStrategy: 按卷追练(5)关键参数', [
            'paper_ids' => $paperIds,
            'kp_code_list' => array_values($paperKnowledgePoints),
            'difficulty_category' => $difficultyCategory,
            'total_questions' => $targetQuestions,
            'total_score' => $maxTotalScore
        ]);

        return $this->buildKnowledgePointAssembleParams($enhanced);
    }

    /**
     * 从错题记录中获取知识点列表（按学生+卷子）
     */
    private function getMistakeKnowledgePointsFromPapers(?string $studentId, array $paperIds): array
    {
        if (empty($studentId) || empty($paperIds)) {
            return [];
        }

        try {
            $records = \App\Models\MistakeRecord::query()
                ->where('student_id', $studentId)
                ->whereIn('paper_id', $paperIds)
                ->get(['kp_ids']);

            $kpCodes = [];
            foreach ($records as $record) {
                $kpIds = $record->kp_ids;
                if (empty($kpIds)) {
                    continue;
                }

                if (is_string($kpIds)) {
                    $decoded = json_decode($kpIds, true);
                    if (is_array($decoded)) {
                        $kpIds = $decoded;
                    }
                }

                if (is_array($kpIds)) {
                    foreach ($kpIds as $kpId) {
                        if (! empty($kpId)) {
                            $kpCodes[$kpId] = true;
                        }
                    }
                }
            }

            return array_values(array_keys($kpCodes));
        } catch (\Exception $e) {
            Log::warning('ExamTypeStrategy: 获取错题知识点失败，回退旧逻辑', [
                'student_id' => $studentId,
                'paper_ids' => $paperIds,
                'error' => $e->getMessage(),
            ]);
            return [];
        }
    }

    /**
     * 从错题记录中获取题目ID列表（用于排除已出现的错题）
     */
    private function getMistakeQuestionIdsFromPapers(?string $studentId, array $paperIds): array
    {
        if (empty($studentId) || empty($paperIds)) {
            return [];
        }

        try {
            return \App\Models\MistakeRecord::query()
                ->where('student_id', $studentId)
                ->whereIn('paper_id', $paperIds)
                ->pluck('question_id')
                ->filter()
                ->unique()
                ->values()
                ->toArray();
        } catch (\Exception $e) {
            Log::warning('ExamTypeStrategy: 获取错题题目ID失败，忽略排除', [
                'student_id' => $studentId,
                'paper_ids' => $paperIds,
                'error' => $e->getMessage(),
            ]);
            return [];
        }
    }

    /**
     * 专项练习：针对特定技能或知识点练习
     */
    private function buildPracticeParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建专项练习参数', $params);

        $studentId = $params['student_id'] ?? null;
        $practiceOptions = $params['practice_options'] ?? [];
        $weaknessThreshold = $practiceOptions['weakness_threshold'] ?? 0.7;
        $intensity = $practiceOptions['intensity'] ?? 'medium';
        $focusWeaknesses = $practiceOptions['focus_weaknesses'] ?? true;

        // 【修复】移除硬编码难度配比，专项练习使用difficulty_category参数
        // 注意：强度调节逻辑已移除，统一使用difficulty_category控制难度分布

        // 获取学生薄弱点
        $weaknessFilter = [];
        if ($studentId && $focusWeaknesses) {
            $weaknessFilter = $this->getStudentWeaknesses($studentId, $weaknessThreshold);
            Log::info('ExamTypeStrategy: 获取到学生薄弱点', [
                'student_id' => $studentId,
                'weakness_threshold' => $weaknessThreshold,
                'weakness_count' => count($weaknessFilter)
            ]);
        }

        // 优先使用薄弱点知识点，如果没有则使用用户选择的知识点
        $kpCodes = $params['kp_codes'] ?? [];
        if ($studentId && empty($kpCodes) && !empty($weaknessFilter)) {
            $kpCodes = array_column($weaknessFilter, 'kp_code');
            Log::info('ExamTypeStrategy: 使用薄弱点作为知识点', [
                'kp_codes' => $kpCodes
            ]);
        }

        $enhanced = array_merge($params, [
            'kp_codes' => $kpCodes,
            // 专项练习更注重题型覆盖
            'question_type_ratio' => [
                '选择题' => 40,
                '填空题' => 30,
                '解答题' => 30,
            ],
            'paper_name' => $params['paper_name'] ?? ('专项练习_' . now()->format('Ymd_His')),
            // 标记这是专项练习，用于后续处理
            'is_practice_exam' => true,
            'weakness_filter' => $weaknessFilter,
        ]);

        Log::info('ExamTypeStrategy: 专项练习参数构建完成（未应用难度分布）', [
            'intensity' => $intensity,
            'difficulty_category' => $params['difficulty_category'] ?? 1,
            'kp_codes_count' => count($enhanced['kp_codes']),
            'weakness_count' => count($weaknessFilter),
            'note' => '将在buildParams中应用difficulty_category难度分布'
        ]);

        return $enhanced;
    }

    /**
     * 教材同步：按教材章节出题
     */
    private function buildTextbookParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建教材同步参数', $params);

        // 教材同步：按章节顺序，难度递增
        // 【修复】移除硬编码难度配比，使用difficulty_category参数
        $textbookOptions = $params['textbook_options'] ?? [];

        $enhanced = array_merge($params, [
            'question_type_ratio' => [
                '选择题' => 40,
                '填空题' => 30,
                '解答题' => 30,
            ],
            'paper_name' => $params['paper_name'] ?? ('教材同步_' . now()->format('Ymd_His')),
            'textbook_options' => $textbookOptions,
        ]);

        Log::info('ExamTypeStrategy: 教材同步参数构建完成（未应用难度分布）', [
            'difficulty_category' => $params['difficulty_category'] ?? 1,
            'note' => '将在buildParams中应用difficulty_category难度分布'
        ]);

        return $enhanced;
    }

    /**
     * 知识点专练：单个或少量知识点深练
     */
    private function buildKnowledgeParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建知识点专练参数', $params);

        // 知识点专练：深度挖掘，多角度考查
        // 【修复】移除硬编码难度配比，使用difficulty_category参数
        $knowledgeOptions = $params['knowledge_options'] ?? [];

        $enhanced = array_merge($params, [
            'question_type_ratio' => [
                '选择题' => 30,
                '填空题' => 35,
                '解答题' => 35,
            ],
            'paper_name' => $params['paper_name'] ?? ('知识点专练_' . now()->format('Ymd_His')),
            'knowledge_options' => $knowledgeOptions,
        ]);

        Log::info('ExamTypeStrategy: 知识点专练参数构建完成（未应用难度分布）', [
            'difficulty_category' => $params['difficulty_category'] ?? 1,
            'note' => '将在buildParams中应用difficulty_category难度分布'
        ]);

        return $enhanced;
    }

    /**
     * 按知识点组卷：根据指定知识点数组智能选题
     * 优先级策略：
     * 1. 直接关联知识点题目（来自输入数组）
     * 2. 相同知识点其他题目
     * 3. 子知识点题目（下探1层）
     * 4. 薄弱点题目比例调整
     * 5. 子知识点题目（下探2层）
     */
    private function buildKnowledgePointsParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建按知识点组卷参数', $params);

        $studentId = $params['student_id'] ?? null;
        $totalQuestions = $params['total_questions'] ?? self::defaultTotalQuestions();
        $knowledgePointsOptions = $params['knowledge_points_options'] ?? [];
        $weaknessThreshold = $knowledgePointsOptions['weakness_threshold'] ?? 0.7;
        $focusWeaknesses = $knowledgePointsOptions['focus_weaknesses'] ?? true;
        $intensity = $knowledgePointsOptions['intensity'] ?? 'medium';

        // 获取用户指定的知识点数组
        $targetKnowledgePoints = $params['kp_codes'] ?? [];
        if (empty($targetKnowledgePoints)) {
            Log::warning('ExamTypeStrategy: 未指定知识点数组，使用默认策略');
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 目标知识点数组', [
            'target_knowledge_points' => $targetKnowledgePoints,
            'count' => count($targetKnowledgePoints)
        ]);

        // 根据强度调整难度配比
        $difficultyRatio = match($intensity) {
            'low' => [
                '基础' => 60,
                '中等' => 35,
                '拔高' => 5,
            ],
            'medium' => [
                '基础' => 45,
                '中等' => 40,
                '拔高' => 15,
            ],
            'high' => [
                '基础' => 30,
                '中等' => 45,
                '拔高' => 25,
            ],
            default => [
                '基础' => 45,
                '中等' => 40,
                '拔高' => 15,
            ]
        };

        // 获取学生薄弱点（用于判断目标知识点是否为薄弱点）
        $weaknessFilter = [];
        if ($studentId && $focusWeaknesses) {
            $weaknessFilter = $this->getStudentWeaknesses($studentId, $weaknessThreshold);
            Log::info('ExamTypeStrategy: 获取到学生薄弱点', [
                'student_id' => $studentId,
                'weakness_threshold' => $weaknessThreshold,
                'weakness_count' => count($weaknessFilter)
            ]);
        }

        // 检查目标知识点中哪些是薄弱点
        $weaknessKpCodes = array_column($weaknessFilter, 'kp_code');
        $targetWeaknessKps = array_intersect($targetKnowledgePoints, $weaknessKpCodes);

        Log::info('ExamTypeStrategy: 目标知识点中的薄弱点', [
            'target_weakness_kps' => $targetWeaknessKps,
            'weakness_count' => count($targetWeaknessKps)
        ]);

        // 使用 QuestionExpansionService 按知识点优先级扩展题目
        // 修改 expandQuestions 支持直接传入知识点数组
        $questionStrategy = $this->questionExpansionService->expandQuestionsByKnowledgePoints(
            $params,
            $studentId,
            $targetKnowledgePoints,
            $weaknessFilter,
            $totalQuestions
        );

        // 获取扩展统计
        $expansionStats = $this->questionExpansionService->getExpansionStats($questionStrategy);

        $enhanced = array_merge($params, [
            'difficulty_ratio' => $difficultyRatio,
            'kp_codes' => $targetKnowledgePoints, // 确保使用目标知识点
            'mistake_question_ids' => $questionStrategy['mistake_question_ids'] ?? [],
            // 优先级知识点：目标知识点 + 薄弱点
            'priority_knowledge_points' => array_merge(
                array_values($targetKnowledgePoints),
                array_column($weaknessFilter, 'kp_code')
            ),
            'question_type_ratio' => [
                '选择题' => 35,
                '填空题' => 30,
                '解答题' => 35,
            ],
            'paper_name' => $params['paper_name'] ?? ('知识点组题_' . now()->format('Ymd_His')),
            // 标记这是按知识点组卷，用于后续处理
            'is_knowledge_points_exam' => true,
            'weakness_filter' => $weaknessFilter,
            // 目标知识点中的薄弱点（用于调整题目数量）
            'target_weakness_kps' => array_values($targetWeaknessKps),
            // 题目扩展统计
            'question_expansion_stats' => $expansionStats
        ]);

        Log::info('ExamTypeStrategy: 按知识点组卷参数构建完成', [
            'intensity' => $intensity,
            'target_knowledge_points_count' => count($targetKnowledgePoints),
            'target_weakness_kps_count' => count($targetWeaknessKps),
            'mistake_question_ids_count' => count($enhanced['mistake_question_ids']),
            'priority_knowledge_points_count' => count($enhanced['priority_knowledge_points']),
            'question_expansion_stats' => $enhanced['question_expansion_stats'],
            'weakness_count' => count($weaknessFilter)
        ]);

        return $enhanced;
    }

    /**
     * 为摸底测试扩展知识点（确保覆盖全面）
     */
    private function expandKpCodesForDiagnostic(array $kpCodes): array
    {
        if (!empty($kpCodes)) {
            return $kpCodes;
        }

        // 如果没有指定知识点，返回一些通用的数学知识点
        return [
            '一元二次方程',
            '二次函数',
            '旋转',
            '圆',
            '概率初步',
        ];
    }

    /**
     * 获取学生薄弱点
     */
    private function getStudentWeaknesses(string $studentId, float $threshold): array
    {
        try {
            // 使用 StudentKnowledgeMastery 模型获取掌握度低于阈值的知识点
            $weaknessRecords = StudentKnowledgeMastery::forStudent($studentId)
                ->weaknesses($threshold)
                ->whereHas('knowledgePoint', function ($query) {
                    $query->whereNotNull('parent_kp_code'); // 排除根节点（如 M00/S000_000）
                })
                ->orderByMastery('asc')
                ->limit(20)
                ->with('knowledgePoint') // 预加载知识点信息
                ->get();

            // 转换为统一格式
            return $weaknessRecords->map(function ($record) {
                return [
                    'kp_code' => $record->kp_code,
                    'kp_name' => $record->knowledgePoint->name ?? $record->kp_code,
                    'mastery' => (float) ($record->mastery_level ?? 0),
                    'attempts' => (int) ($record->total_attempts ?? 0),
                    'correct' => (int) ($record->correct_attempts ?? 0),
                    'incorrect' => (int) ($record->incorrect_attempts ?? 0),
                    'confidence' => (float) ($record->confidence_level ?? 0),
                    'trend' => $record->mastery_trend ?? 'stable',
                ];
            })->toArray();

        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 获取学生薄弱点失败', [
                'student_id' => $studentId,
                'threshold' => $threshold,
                'error' => $e->getMessage()
            ]);

            return [];
        }
    }

    /**
     * 智能组卷 (assembleType=8, 兼容旧 assembleType=1)
     * 基于教材知识点顺序与学生掌握度，选择首个未达标知识点（或其列表）组卷
     */
    private function buildIntelligentAssembleParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建智能组卷参数', $params);

        $textbookId = $params['textbook_id'] ?? null;
        $grade = $params['grade'] ?? null; // 年级信息
        $totalQuestions = $params['total_questions'] ?? self::defaultTotalQuestions();
        $studentId = (int) ($params['student_id'] ?? 0);

        if (!$textbookId) {
            Log::warning('ExamTypeStrategy: 智能组卷需要 textbook_id 参数');
            return $this->buildGeneralParams($params);
        }

        $diagnosticService = app(DiagnosticChapterService::class);
        $textbookKpCodes = $diagnosticService->getTextbookKnowledgePointsInOrder((int) $textbookId);

        if (empty($textbookKpCodes)) {
            Log::warning('ExamTypeStrategy: 教材未找到知识点', ['textbook_id' => $textbookId]);
            return $this->buildGeneralParams($params);
        }

        $masteryMap = [];
        if ($studentId) {
            $masteryMap = StudentKnowledgeMastery::query()
                ->where('student_id', $studentId)
                ->whereIn('kp_code', $textbookKpCodes)
                ->pluck('mastery_level', 'kp_code')
                ->toArray();
        }

        $matchedKpCodes = array_values(array_intersect($textbookKpCodes, array_keys($masteryMap)));

        if (empty($matchedKpCodes)) {
            $initial = $diagnosticService->getInitialChapterKnowledgePoints((int) $textbookId);
            $kpCodes = $initial['kp_codes'] ?? [];

            if (empty($kpCodes)) {
                Log::warning('ExamTypeStrategy: 智能组卷未找到首章知识点', [
                    'textbook_id' => $textbookId
                ]);
                return $this->buildGeneralParams($params);
            }
        } else {
            $kpCodes = [];
            foreach ($textbookKpCodes as $kpCode) {
                if (!isset($masteryMap[$kpCode])) {
                    continue;
                }

                $level = (float) $masteryMap[$kpCode];
                if ($level < 0.9) {
                    $kpCodes[] = $kpCode;
                }
            }

            if (empty($kpCodes)) {
                $initial = $diagnosticService->getInitialChapterKnowledgePoints((int) $textbookId);
                $kpCodes = $initial['kp_codes'] ?? [];
            }
        }

        Log::info('ExamTypeStrategy: 获取到知识点', [
            'kp_count' => count($kpCodes),
            'kp_codes' => array_slice($kpCodes, 0, 5)
        ]);

        // 【重要】grade 缺失时从教材推断，保证智能补充可触发
        if ($textbookId && ($grade === null || $grade === '')) {
            $grade = DB::table('textbooks')->where('id', $textbookId)->value('grade');
            Log::info('ExamTypeStrategy: 智能组卷从教材推断 grade', [
                'textbook_id' => $textbookId,
                'inferred_grade' => $grade
            ]);
        }

        // 组装增强参数
        $enhanced = array_merge($params, [
            'kp_code_list' => $kpCodes,
            'textbook_id' => $textbookId,
            'grade' => $grade,
            'paper_name' => $params['paper_name'] ?? ('智能组题_' . now()->format('Ymd_His')),
            // 智能组卷：平衡的题型和难度配比
            'question_type_ratio' => [
                '选择题' => 40,
                '填空题' => 30,
                '解答题' => 30,
            ],
            'difficulty_ratio' => [
                '基础' => 25,
                '中等' => 50,
                '拔高' => 25,
            ],
            'question_category' => 0, // question_category=0 代表普通题目（智能组卷）
            'is_intelligent_assemble' => true,
        ]);

        Log::info('ExamTypeStrategy: 智能组卷参数构建完成', [
            'textbook_id' => $textbookId,
            'grade' => $grade,
            'kp_count' => count($kpCodes),
            'total_questions' => $totalQuestions
        ]);

        return $this->buildKnowledgePointAssembleParams($enhanced);
    }

    /**
     * 知识点组卷 (assembleType=2)
     * 直接根据 kp_code_list 查询题目，排除已做过的题目
     */
    private function buildKnowledgePointAssembleParams(array $params): array
    {
        Log::info('ExamTypeStrategy: 构建知识点组卷参数', $params);

        $kpCodeList = $params['kp_code_list'] ?? [];
        if (!is_array($kpCodeList)) {
            $kpCodeList = [];
        }
        $kpCodeList = array_values(array_unique(array_filter($kpCodeList)));
        $studentId = $params['student_id'] ?? null;
        $totalQuestions = $params['total_questions'] ?? self::defaultTotalQuestions();
        $assembleType = (int) ($params['assemble_type'] ?? 4);

        if (empty($kpCodeList)) {
            Log::warning('ExamTypeStrategy: 知识点组卷需要 kp_code_list 参数');
            return $this->buildGeneralParams($params);
        }

        // 本源选题用原始 kp；父节点整树仅作为「本源不足时」的补题 KP（见 kp_supplement_subtree_codes → LearningAnalyticsService）
        $kpSupplementSubtreeCodes = [];
        if ($assembleType === 2) {
            $expandedKpCodes = $this->expandKpCodesWithParentChapterSubtrees($kpCodeList);
            $kpSupplementSubtreeCodes = array_values(array_diff($expandedKpCodes, $kpCodeList));
            Log::info('ExamTypeStrategy: 知识点组卷父树仅用于补题 KP（本源优先）', [
                'original_kp_codes' => $kpCodeList,
                'supplement_kp_codes' => $kpSupplementSubtreeCodes,
                'original_count' => count($kpCodeList),
                'supplement_count' => count($kpSupplementSubtreeCodes),
            ]);
        }

        Log::debug('ExamTypeStrategy: 知识点组卷', [
            'kp_count' => count($kpCodeList),
            'supplement_kp_count' => count($kpSupplementSubtreeCodes),
            'total_questions' => $totalQuestions
        ]);

        // assemble_type=2 走知识点扩展策略（复用 QuestionExpansionService）。
        // 只在基础题池不足时，才会触发子知识点补充（由扩展策略内部控制）。
        $priorityQuestionIds = [];
        $basePoolCount = 0;
        $finalPoolCount = 0;
        $childAddedCount = 0;

        if ($assembleType === 2) {
            $expansionStrategy = $this->questionExpansionService->expandQuestionsByKnowledgePoints(
                $params,
                $studentId ? (string) $studentId : null,
                $kpCodeList,
                [],
                (int) $totalQuestions
            );

            $priorityQuestionIds = array_values(array_unique(array_filter($expansionStrategy['mistake_question_ids'] ?? [])));
            $basePoolCount = (int) (
                ($expansionStrategy['expansion_details']['step1_direct_kp']['added_count'] ?? 0)
                + ($expansionStrategy['expansion_details']['step2_same_kp']['added_count'] ?? 0)
            );
            $finalPoolCount = count($priorityQuestionIds);
            $childAddedCount = max(0, $finalPoolCount - $basePoolCount);
        }

        // 如果有学生ID，获取已做过的题目ID列表（用于排除）
        $answeredQuestionIds = [];
        if ($studentId) {
            $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodeList);
        }

        Log::debug('ExamTypeStrategy: 知识点组卷题池评估', [
            'kp_count' => count($kpCodeList),
            'supplement_kp_count' => count($kpSupplementSubtreeCodes),
            'pool_count' => $finalPoolCount,
            'exclude_count' => count($answeredQuestionIds),
        ]);

        // 组装增强参数
        $enhanced = array_merge($params, [
            'kp_codes' => $kpCodeList,
            'kp_supplement_subtree_codes' => $kpSupplementSubtreeCodes,
            'kp_code_list_original' => $kpCodeList,
            'mistake_question_ids' => $basePoolCount < (int) $totalQuestions ? $priorityQuestionIds : [],
            'exclude_question_ids' => $answeredQuestionIds,
            'paper_name' => $params['paper_name'] ?? ('知识点组题_' . now()->format('Ymd_His')),
            // 知识点组卷：442配比（配合固定分值5/5/10，各题型贡献均等）
            'question_type_ratio' => [
                '选择题' => 40,
                '填空题' => 40,
                '解答题' => 20,
            ],
            'difficulty_ratio' => [
                '基础' => 25,
                '中等' => 50,
                '拔高' => 25,
            ],
            'question_category' => 0, // question_category=0 代表普通题目
            'is_knowledge_point_assemble' => true,
        ]);

        Log::debug('ExamTypeStrategy: 知识点组卷参数构建完成', [
            'kp_count' => count($kpCodeList),
            'supplement_kp_count' => count($kpSupplementSubtreeCodes),
            'exclude_count' => count($answeredQuestionIds),
        ]);

        return $enhanced;
    }

    /**
     * 将用户选中的 kp 扩展为：各选中知识点在 knowledge_points 中「直接父节点」下的整棵子树（含父节点自身及所有后代）之并集。
     * 多选且同属同一父章节（如 SIM01 下的 SIM01B/C/D）时，distinct parent 仅为 SIM01，等价于纳入 SIM01 整棵树（SIM01A–E 等）的全部 kp_code。
     * 不在此再上溯祖父：祖父在库中往往挂在更高层（如整册根），会造成超范围并题。
     *
     * @return array<string>
     */
    private function expandKpCodesWithParentChapterSubtrees(array $kpCodes): array
    {
        $kpCodes = array_values(array_unique(array_filter($kpCodes)));
        if ($kpCodes === []) {
            return [];
        }

        $expanded = [];
        foreach ($kpCodes as $kp) {
            $expanded[] = $kp;
        }

        $distinctParents = [];
        foreach ($kpCodes as $kp) {
            $p = KnowledgePoint::query()->where('kp_code', $kp)->value('parent_kp_code');
            if ($p !== null && $p !== '') {
                $distinctParents[(string) $p] = true;
            }
        }

        foreach (array_keys($distinctParents) as $parentKp) {
            $expanded = array_merge($expanded, $this->getDescendantKpCodesIncludingRoot($parentKp));
        }

        return array_values(array_unique(array_filter($expanded)));
    }

    /**
     * BFS 收集某 kp 节点在 knowledge_points 中的整棵后代子树（含根节点 kp_code）。
     *
     * @return array<string>
     */
    private function getDescendantKpCodesIncludingRoot(string $rootKpCode): array
    {
        $rootKpCode = trim($rootKpCode);
        if ($rootKpCode === '') {
            return [];
        }

        $seen = [$rootKpCode => true];
        $queue = [$rootKpCode];
        $guard = 0;
        $maxIter = 5000;

        while ($queue !== [] && $guard++ < $maxIter) {
            $cur = array_shift($queue);
            $children = KnowledgePoint::query()
                ->where('parent_kp_code', $cur)
                ->pluck('kp_code')
                ->all();

            foreach ($children as $child) {
                $c = (string) $child;
                if ($c === '') {
                    continue;
                }
                if (! isset($seen[$c])) {
                    $seen[$c] = true;
                    $queue[] = $c;
                }
            }
        }

        return array_keys($seen);
    }

    /**
     * 教材组卷 (assembleType=3)
     * 根据 chapter_id_list 查询课本章节，获取知识点，然后组卷
     * 优化：按textbook_catalog_node_id筛选题目，添加章节知识点数量统计
     */
    private function buildTextbookAssembleParams(array $params): array
    {
        Log::debug('ExamTypeStrategy: 构建教材组卷参数', [
            'chapter_count' => count($params['chapter_id_list'] ?? []),
            'textbook_id' => $params['textbook_id'] ?? null
        ]);

        $chapterIdList = $params['chapter_id_list'] ?? [];
        $studentId = $params['student_id'] ?? null;
        $totalQuestions = $params['total_questions'] ?? self::defaultTotalQuestions();

        // 【优化】如果用户没有指定章节，自动从教材所有有题目的章节中选择
        if (empty($chapterIdList) && !empty($params['textbook_id'])) {
            Log::info('ExamTypeStrategy: 用户未指定章节，自动从教材选择', [
                'textbook_id' => $params['textbook_id']
            ]);

            // 【修复】先查询教材下的所有章节，再筛选有题目的章节
            // 步骤1：根据textbook_id获取该教材下的所有章节ID
            $allChapterIds = DB::table('textbook_catalog_nodes')
                ->where('textbook_id', $params['textbook_id'])
                ->where('node_type', 'section')
                ->pluck('id')
                ->toArray();

            if (empty($allChapterIds)) {
                Log::warning('ExamTypeStrategy: 教材下未找到章节', [
                    'textbook_id' => $params['textbook_id']
                ]);
            } else {
                // 步骤2：从这些章节中筛选出有题目的章节
                $chapterIdList = DB::table('questions')
                    ->whereIn('textbook_catalog_nodes_id', $allChapterIds)
                    ->whereNotNull('textbook_catalog_nodes_id')
                    ->where('textbook_catalog_nodes_id', '!=', '')
                    ->distinct()
                    ->pluck('textbook_catalog_nodes_id')
                    ->toArray();

                Log::info('ExamTypeStrategy: 自动选择的章节列表', [
                    'textbook_id' => $params['textbook_id'],
                    'total_chapters' => count($allChapterIds),
                    'chapters_with_questions' => count($chapterIdList),
                    'chapter_ids' => $chapterIdList
                ]);
            }
        }

        // 【新增】如果用户指定了章节，解析章节节点类型并获取所有section/subsection节点
        if (!empty($chapterIdList)) {
            Log::info('ExamTypeStrategy: 用户指定了章节，开始解析节点类型', [
                'input_chapter_ids' => $chapterIdList
            ]);

            // 解析用户传入的chapter_id_list，获取所有section/subsection节点
            $resolvedSectionIds = $this->resolveSectionNodesFromChapters($chapterIdList);

            if (!empty($resolvedSectionIds)) {
                // 使用解析后的section/subsection节点ID替换原有的chapterIdList
                $originalChapterCount = count($chapterIdList);
                $chapterIdList = $resolvedSectionIds;

                Log::info('ExamTypeStrategy: 章节节点解析完成，使用解析后的节点', [
                    'original_count' => $originalChapterCount,
                    'resolved_count' => count($chapterIdList),
                    'resolved_ids' => $chapterIdList
                ]);
            } else {
                Log::warning('ExamTypeStrategy: 章节节点解析失败，使用原始节点列表', [
                    'chapter_id_list' => $chapterIdList
                ]);
            }
        }

        if (empty($chapterIdList)) {
            Log::warning('ExamTypeStrategy: 教材组卷需要 chapter_id_list 参数或有效的textbook_id');
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 教材组卷', [
            'chapter_id_list' => $chapterIdList,
            'student_id' => $studentId,
            'total_questions' => $totalQuestions
        ]);

        // 【修复】第一步：根据章节ID查询知识点关联，并统计每个章节的知识点数量
        $kpCodes = $this->getKnowledgePointsFromChapters($chapterIdList);

        // 【新增】获取每个章节对应的知识点数量统计
        $chapterKnowledgePointStats = $this->getChapterKnowledgePointStats($chapterIdList);

        Log::info('ExamTypeStrategy: 获取章节知识点统计', [
            'chapter_stats' => $chapterKnowledgePointStats,
            'total_chapters' => count($chapterIdList)
        ]);

        // 【重要】教材组卷严格限制知识点数量，不进行任何扩展
        if (empty($kpCodes)) {
            Log::warning('ExamTypeStrategy: 未找到章节知识点关联，但保留章节筛选参数', [
                'chapter_id_list' => $chapterIdList,
                'note' => 'LearningAnalyticsService 将按 textbook_chapter_knowledge_relation 解析知识点后按 kp_code 选题',
            ]);
        } else {
            Log::info('ExamTypeStrategy: 获取章节知识点（教材组卷严格限制）', [
                'kp_count' => count($kpCodes),
                'kp_codes' => $kpCodes,
                'note' => '教材组卷只返回章节关联的知识点，不进行扩展'
            ]);
        }

        // 第二步：如果有学生ID，获取已做过的题目ID列表（用于排除）
        $answeredQuestionIds = [];
        if ($studentId) {
            $answeredQuestionIds = $this->getStudentAnsweredQuestionIds($studentId, $kpCodes);
            Log::info('ExamTypeStrategy: 获取学生已答题目', [
                'student_id' => $studentId,
                'answered_count' => count($answeredQuestionIds)
            ]);
        }

        // 【优化】第三步：按textbook_catalog_node_id筛选题目，添加筛选条件
        // 在LearningAnalyticsService中会使用这些参数进行题目筛选
        $textbookCatalogNodeIds = $chapterIdList; // 直接使用章节ID作为textbook_catalog_node_id筛选条件

        // 【重要】确保 grade 和 textbook_id 传给智能补充；章节节点归属教材，可由 chapter_id_list 反查 textbook_id
        $textbookId = (int) ($params['textbook_id'] ?? 0);
        if ($textbookId <= 0 && ! empty($chapterIdList)) {
            $resolvedTextbookId = $this->resolveTextbookIdFromChapterNodes($chapterIdList);
            if ($resolvedTextbookId !== null) {
                $textbookId = $resolvedTextbookId;
                Log::info('ExamTypeStrategy: 由 chapter_id_list 推断 textbook_id', [
                    'textbook_id' => $textbookId,
                    'chapter_id_list' => $chapterIdList,
                ]);
            }
        }

        $grade = $params['grade'] ?? null;
        if ($textbookId && $grade === null) {
            $grade = DB::table('textbooks')->where('id', $textbookId)->value('grade');
            Log::info('ExamTypeStrategy: 教材组卷从教材推断 grade', [
                'textbook_id' => $textbookId,
                'inferred_grade' => $grade
            ]);
        }

        // 组装增强参数
        $enhanced = array_merge($params, [
            'kp_codes' => $kpCodes, // 可能为空，但仍保留
            'chapter_id_list' => $chapterIdList,
            'textbook_id' => $textbookId ?: ($params['textbook_id'] ?? null), // 保证智能补充有教材范围
            'grade' => $grade,
            'textbook_catalog_node_ids' => $textbookCatalogNodeIds, // 【重要】即使kpCodes为空也设置此参数
            'exclude_question_ids' => $answeredQuestionIds,
            'paper_name' => $params['paper_name'] ?? ('教材组题_' . now()->format('Ymd_His')),
            // 教材组卷：按教材特点分配题型
            'question_type_ratio' => [
                '选择题' => 40,
                '填空题' => 30,
                '解答题' => 30,
            ],
            'difficulty_ratio' => [
                '基础' => 25,
                '中等' => 50,
                '拔高' => 25,
            ],
            'question_category' => 0, // question_category=0 代表普通题目
            'is_textbook_assemble' => true,
            // 【新增】章节知识点数量统计
            'chapter_knowledge_point_stats' => $chapterKnowledgePointStats,
        ]);

        Log::info('ExamTypeStrategy: 教材组卷参数构建完成', [
            'chapter_count' => count($chapterIdList),
            'kp_count' => count($kpCodes),
            'exclude_count' => count($answeredQuestionIds),
            'total_questions' => $totalQuestions,
            'chapter_stats' => $chapterKnowledgePointStats
        ]);

        return $enhanced;
    }

    /**
     * 章节节点 textbook_catalog_nodes 均归属某本教材；未传 textbook_id 时可根据节点 id 反查。
     *
     * @param  array<int|string>  $chapterIdList  解析后的章节/小节节点 id 列表
     * @return int|null  唯一教材 id；无法解析或节点不存在时返回 null
     */
    private function resolveTextbookIdFromChapterNodes(array $chapterIdList): ?int
    {
        $ids = array_values(array_unique(array_filter(array_map(
            static fn ($id) => (int) $id,
            $chapterIdList
        ), static fn (int $id) => $id > 0)));

        if ($ids === []) {
            return null;
        }

        $textbookIds = DB::table('textbook_catalog_nodes')
            ->whereIn('id', $ids)
            ->pluck('textbook_id')
            ->unique()
            ->values()
            ->all();

        if ($textbookIds === []) {
            Log::warning('ExamTypeStrategy: chapter_id_list 在 textbook_catalog_nodes 中无匹配行', [
                'chapter_ids' => $ids,
            ]);

            return null;
        }

        if (count($textbookIds) > 1) {
            Log::warning('ExamTypeStrategy: chapter_id_list 对应多本教材，取首个 textbook_id', [
                'textbook_ids' => $textbookIds,
                'chapter_ids' => $ids,
            ]);
        }

        return (int) $textbookIds[0];
    }

    /**
     * 根据课本ID获取章节ID列表
     * @param int $textbookId 教材ID
     * @param int|null $endCatalogId 截止章节ID（仅摸底使用），只返回该章节及之前的章节
     */
    private function getTextbookChapterIds(int $textbookId, ?int $endCatalogId = null): array
    {
        try {
            $query = DB::table('textbook_catalog_nodes')
                ->where('textbook_id', $textbookId)
                ->where('node_type', 'section') // nodeType='section'
                ->orderBy('sort_order');

            // 如果指定了截止章节，只获取该章节及之前的章节
            if ($endCatalogId) {
                $endSortOrder = DB::table('textbook_catalog_nodes')
                    ->where('id', $endCatalogId)
                    ->value('sort_order');

                if ($endSortOrder !== null) {
                    $query->where('sort_order', '<=', $endSortOrder);
                    Log::debug('ExamTypeStrategy: 应用截止章节过滤', [
                        'end_catalog_id' => $endCatalogId,
                        'end_sort_order' => $endSortOrder
                    ]);
                } else {
                    Log::warning('ExamTypeStrategy: 截止章节ID无效', [
                        'end_catalog_id' => $endCatalogId
                    ]);
                }
            }

            $chapterIds = $query->pluck('id')->toArray();

            Log::debug('ExamTypeStrategy: 查询课本章节ID', [
                'textbook_id' => $textbookId,
                'end_catalog_id' => $endCatalogId,
                'found_count' => count($chapterIds)
            ]);

            return $chapterIds;
        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 查询课本章节ID失败', [
                'textbook_id' => $textbookId,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 根据章节ID列表获取知识点代码列表（均等抽样版本）
     * 使用"知识点均等抽样"算法，确保覆盖全书章节
     *
     * @param array $chapterIds 章节ID列表
     * @param int $limit 目标题目数量（默认25）
     * @return array 抽样后的知识点代码列表
     */
    private function getKnowledgePointsFromChapters(array $chapterIds, int $limit = 25): array
    {
        try {
            // 如果章节数较少，使用原有逻辑
            if (count($chapterIds) <= 15) {
                Log::info('ExamTypeStrategy: 章节数较少，使用原有逻辑', [
                    'chapter_count' => count($chapterIds)
                ]);
                return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
            }

            // ========== 步骤1: 构建全量有序池 ==========
            // 查询所有知识点，按章节顺序排列，去重后得到有序数组
            $allKpData = DB::table('textbook_chapter_knowledge_relation as tckr')
                ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
                ->whereIn('tckr.catalog_chapter_id', $chapterIds)
                ->where(function ($q) {
                    $q->where('tckr.is_deleted', 0)->orWhereNull('tckr.is_deleted');
                })
                ->select('tckr.kp_code', 'tcn.sort_order', 'tcn.id as chapter_id', 'tcn.title as chapter_title')
                ->orderBy('tcn.sort_order', 'asc')
                ->orderBy('tckr.kp_code', 'asc')
                ->get();

            // 去重并构建有序数组
            $allKpCodes = [];
            $chapterInfo = [];
            foreach ($allKpData as $row) {
                if (!in_array($row->kp_code, $allKpCodes)) {
                    $allKpCodes[] = $row->kp_code;
                    $chapterInfo[$row->kp_code] = [
                        'chapter_id' => $row->chapter_id,
                        'chapter_title' => $row->chapter_title,
                        'sort_order' => $row->sort_order
                    ];
                }
            }

            $totalKps = count($allKpCodes);

            Log::info('ExamTypeStrategy: 构建全量有序池完成', [
                'chapter_count' => count($chapterIds),
                'total_knowledge_points' => $totalKps,
                'target_questions' => $limit
            ]);

            // ========== 步骤2: 计算抽样步长 ==========
            $step = $totalKps > 0 ? $totalKps / $limit : 1;
            Log::info('ExamTypeStrategy: 计算抽样步长', [
                'step' => $step
            ]);

            // ========== 步骤3: 等距取样 ==========
            $selectedKps = [];
            $selectedCount = 0;
            $currentIndex = 0;

            while ($selectedCount < $limit && $selectedCount < $totalKps) {
                $index = (int) floor($currentIndex);
                if ($index < $totalKps && isset($allKpCodes[$index])) {
                    $kpCode = $allKpCodes[$index];
                    if (!in_array($kpCode, $selectedKps)) {
                        $selectedKps[] = $kpCode;
                        $selectedCount++;
                    }
                }
                $currentIndex += $step;
            }

            // 如果数量不足，循环取样
            if (count($selectedKps) < $limit && $totalKps > 0) {
                Log::info('ExamTypeStrategy: 第一次抽样不足，进行循环取样', [
                    'selected_count' => count($selectedKps),
                    'target_count' => $limit
                ]);

                $needed = $limit - count($selectedKps);
                $startIndex = 0;

                for ($i = 0; $i < $needed && count($selectedKps) < $limit; $i++) {
                    $index = ($startIndex + $i) % $totalKps;
                    $kpCode = $allKpCodes[$index];
                    if (!in_array($kpCode, $selectedKps)) {
                        $selectedKps[] = $kpCode;
                    }
                }
            }

            // ========== 步骤4: 记录抽样统计 ==========
            $chapterDistribution = [];
            foreach ($selectedKps as $kpCode) {
                if (isset($chapterInfo[$kpCode])) {
                    $chapterId = $chapterInfo[$kpCode]['chapter_id'];
                    if (!isset($chapterDistribution[$chapterId])) {
                        $chapterDistribution[$chapterId] = [
                            'count' => 0,
                            'title' => $chapterInfo[$kpCode]['chapter_title']
                        ];
                    }
                    $chapterDistribution[$chapterId]['count']++;
                }
            }

            Log::info('ExamTypeStrategy: 等距抽样完成', [
                'total_kps' => $totalKps,
                'selected_kps' => count($selectedKps),
                'step' => $step,
                'chapter_distribution' => $chapterDistribution,
                'sample_kp_codes' => array_slice($selectedKps, 0, 10)
            ]);

            return array_filter($selectedKps);

        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 均等抽样获取章节知识点失败，使用原有逻辑', [
                'chapter_ids' => $chapterIds,
                'error' => $e->getMessage()
            ]);

            // 失败时回退到原有逻辑
            return $this->getKnowledgePointsFromChaptersLegacy($chapterIds, $limit);
        }
    }

    /**
     * 原有逻辑（保留作为回退方案）
     * 修复：解决DISTINCT和ORDER BY冲突问题
     */
    private function getKnowledgePointsFromChaptersLegacy(array $chapterIds, int $limit = 25): array
    {
        try {
            // 修复方案1：使用GROUP BY替代DISTINCT，并选择需要的字段
            $kpCodes = DB::table('textbook_chapter_knowledge_relation')
                ->whereIn('catalog_chapter_id', $chapterIds)
                ->where(function ($q) {
                    $q->where('is_deleted', 0)->orWhereNull('is_deleted');
                })
                ->select('kp_code')
                ->groupBy('kp_code')
                ->pluck('kp_code')
                ->toArray();
            Log::debug('ExamTypeStrategy: 查询章节知识点（原有逻辑）', [
                'chapter_count' => count($chapterIds),
                'found_kp_count' => count($kpCodes)
            ]);

            return array_filter($kpCodes); // 移除空值
        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 查询章节知识点失败', [
                'chapter_ids' => $chapterIds,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 获取学生已做题目ID列表（用于排除）
     *
     * 唯一来源：从 paper_questions 中取该学生名下所有试卷的题目 ID（questions.id）
     * 确保新卷子不会出现学生做过的重复题目
     */
    private function getStudentAnsweredQuestionIds(string $studentId, array $kpCodes): array
    {
        try {
            $questionIds = PaperQuestion::query()
                ->whereHas('paper', fn ($q) => $q->where('student_id', $studentId))
                ->whereNotNull('question_bank_id')
                ->where('question_bank_id', '>', 0)
                ->distinct()
                ->pluck('question_bank_id')
                ->map(fn ($v) => (int) $v)
                ->values()
                ->toArray();

            Log::debug('ExamTypeStrategy: 从 paper_questions 获取学生已做题目', [
                'student_id' => $studentId,
                'exclude_count' => count($questionIds),
            ]);

            return $questionIds;
        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 获取学生已做题目失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 通过卷子ID列表查询错题
     * 注意：paper_ids 使用的是 papers 表中的 paper_id 字段，不是 id 字段
     * 错题数据从 mistake_records 表中获取，该表已包含 paper_id 字段
     * 注意：不按学生ID过滤，因为卷子可能包含其他同学的错题，需要收集所有错题
     */
    private function getMistakeQuestionsFromPapers(array $paperIds, ?string $studentId = null): array
    {
        try {
            // 使用 Eloquent 模型查询，从 mistake_records 表中获取错题记录
            // 不按 student_id 过滤，因为要收集所有学生的错题
            $mistakeRecords = MistakeRecord::query()
                ->whereIn('paper_id', $paperIds)
                ->get();

            if ($mistakeRecords->isEmpty()) {
                Log::warning('ExamTypeStrategy: 卷子中未找到错题记录', [
                    'paper_ids' => $paperIds
                ]);
                return [];
            }

            // 收集所有错题的 question_id
            $questionIds = $mistakeRecords->pluck('question_id')
                ->filter()
                ->unique()
                ->values()
                ->toArray();

            Log::info('ExamTypeStrategy: 查询卷子错题完成', [
                'paper_count' => count($paperIds),
                'paper_ids_input' => $paperIds,
                'mistake_record_count' => $mistakeRecords->count(),
                'unique_question_count' => count($questionIds),
                'question_ids' => array_slice($questionIds, 0, 20), // 最多记录20个ID
                'per_paper_stats' => $mistakeRecords->groupBy('paper_id')->map->count()->toArray()
            ]);

            return array_filter($questionIds);

        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 查询卷子错题失败', [
                'paper_ids' => $paperIds,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 通过题目ID列表获取知识点代码列表
     */
    private function getKnowledgePointsFromQuestions(array $questionIds): array
    {
        try {
            // 使用 Eloquent 模型查询，获取题目的知识点
            $questions = Question::whereIn('id', $questionIds)
                ->whereNotNull('kp_code')
                ->where('kp_code', '!=', '')
                ->distinct()
                ->pluck('kp_code')
                ->toArray();

            Log::debug('ExamTypeStrategy: 查询题目知识点', [
                'question_count' => count($questionIds),
                'kp_count' => count($questions)
            ]);

            return array_filter($questions);
        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 查询题目知识点失败', [
                'question_ids' => array_slice($questionIds, 0, 10), // 只记录前10个
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 通过卷子ID列表获取卷子题目ID
     */
    private function getQuestionIdsFromPapers(array $paperIds): array
    {
        try {
            $questionIds = DB::table('paper_questions')
                ->whereIn('paper_id', $paperIds)
                ->pluck('question_bank_id')
                ->unique()
                ->filter()
                ->values()
                ->toArray();

            Log::debug('ExamTypeStrategy: 获取卷子题目ID', [
                'paper_ids' => $paperIds,
                'question_count' => count($questionIds)
            ]);

            return $questionIds;
        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 获取卷子题目ID失败', [
                'paper_ids' => $paperIds,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 通过卷子ID列表获取题目知识点（直接使用 paper_questions.knowledge_point）
     */
    private function getKnowledgePointsFromPaperQuestions(array $paperIds): array
    {
        try {
            $knowledgePoints = DB::table('paper_questions')
                ->whereIn('paper_id', $paperIds)
                ->whereNotNull('knowledge_point')
                ->where('knowledge_point', '!=', '')
                ->pluck('knowledge_point')
                ->unique()
                ->filter()
                ->values()
                ->toArray();

            Log::debug('ExamTypeStrategy: 获取卷子题目知识点', [
                'paper_ids' => $paperIds,
                'kp_count' => count($knowledgePoints),
            ]);

            return $knowledgePoints;
        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 获取卷子题目知识点失败', [
                'paper_ids' => $paperIds,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 通过卷子ID列表获取难度/题量/总分的聚合信息
     */
    private function getPaperAggregateStats(array $paperIds): array
    {
        try {
            $rows = DB::table('papers')
                ->whereIn('paper_id', $paperIds)
                ->select(['paper_id', 'difficulty_category', 'total_questions', 'total_score'])
                ->get();

            $perPaper = [];
            $difficultyValues = [];
            $questionValues = [];
            $scoreValues = [];
            foreach ($rows as $row) {
                $difficulty = is_null($row->difficulty_category) ? null : (int) $row->difficulty_category;
                $totalQuestions = is_null($row->total_questions) ? null : (int) $row->total_questions;
                $totalScore = is_null($row->total_score) ? null : (float) $row->total_score;

                $perPaper[$row->paper_id] = [
                    'difficulty_category' => $difficulty,
                    'total_questions' => $totalQuestions,
                    'total_score' => $totalScore,
                    'raw_total_questions' => $row->total_questions,
                ];

                if (!is_null($difficulty)) {
                    $difficultyValues[] = $difficulty;
                }
                if (!empty($totalQuestions)) {
                    $questionValues[] = $totalQuestions;
                }
                if (!is_null($totalScore)) {
                    $scoreValues[] = $totalScore;
                }
            }

            $stats = [
                'difficulty_category_min' => empty($difficultyValues) ? null : min($difficultyValues),
                'total_questions_max' => empty($questionValues) ? null : max($questionValues),
                'total_score_max' => empty($scoreValues) ? null : max($scoreValues),
            ];

            if (empty($stats['total_questions_max'])) {
                $stats['total_questions_max'] = DB::table('paper_questions')
                    ->whereIn('paper_id', $paperIds)
                    ->selectRaw('paper_id, COUNT(*) as cnt')
                    ->groupBy('paper_id')
                    ->pluck('cnt')
                    ->max();
            }

            Log::info('ExamTypeStrategy: 获取卷子聚合信息', [
                'paper_ids' => $paperIds,
                'per_paper' => $perPaper,
                'stats' => $stats,
            ]);

            return $stats;
        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 获取卷子聚合信息失败', [
                'paper_ids' => $paperIds,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    /**
     * 【新增】获取每个章节对应的知识点数量统计
     * 通过textbook_chapter_knowledge_relation表关联查询
     *
     * @param array $chapterIdList 章节ID列表
     * @return array 章节知识点数量统计
     */
    private function getChapterKnowledgePointStats(array $chapterIdList): array
    {
        try {
            // 查询每个章节对应的知识点数量
            $stats = DB::table('textbook_chapter_knowledge_relation as tckr')
                ->join('textbook_catalog_nodes as tcn', 'tckr.catalog_chapter_id', '=', 'tcn.id')
                ->whereIn('tckr.catalog_chapter_id', $chapterIdList)
                ->where(function ($q) {
                    $q->where('tckr.is_deleted', 0)->orWhereNull('tckr.is_deleted');
                })
                ->select(
                    'tckr.catalog_chapter_id as chapter_id',
                    'tcn.title as chapter_title',
                    DB::raw('COUNT(DISTINCT tckr.kp_code) as knowledge_point_count')
                )
                ->groupBy('tckr.catalog_chapter_id', 'tcn.title')
                ->orderBy('tckr.catalog_chapter_id')
                ->get();

            // 转换为数组格式
            $result = [];
            foreach ($stats as $stat) {
                $result[] = [
                    'chapter_id' => $stat->chapter_id,
                    'chapter_title' => $stat->chapter_title,
                    'knowledge_point_count' => (int) $stat->knowledge_point_count
                ];
            }

            Log::debug('ExamTypeStrategy: 获取章节知识点统计', [
                'chapter_count' => count($chapterIdList),
                'stats_count' => count($result),
                'stats' => $result
            ]);

            return $result;

        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 获取章节知识点统计失败', [
                'chapter_id_list' => $chapterIdList,
                'error' => $e->getMessage()
            ]);

            // 返回空数组，不影响组卷流程
            return [];
        }
    }

    /**
     * 【新增】递归获取section节点ID列表
     * 根据用户传入的chapter_id_list，自动识别节点类型：
     * - 如果是chapter节点，查找其下的所有section子节点（不包含subsection）
     * - 如果是section节点，直接使用
     *
     * @param array $chapterIdList 用户传入的章节ID列表
     * @return array 最终用于查询知识点的section节点ID列表
     */
    private function resolveSectionNodesFromChapters(array $chapterIdList): array
    {
        try {
            if (empty($chapterIdList)) {
                return [];
            }

            Log::info('ExamTypeStrategy: 开始解析章节节点', [
                'input_chapter_ids' => $chapterIdList
            ]);

            $finalSectionIds = [];

            foreach ($chapterIdList as $nodeId) {
                // 查询节点信息
                $node = DB::table('textbook_catalog_nodes')
                    ->where('id', $nodeId)
                    ->first();

                if (!$node) {
                    Log::warning('ExamTypeStrategy: 未找到节点', ['node_id' => $nodeId]);
                    continue;
                }

                Log::debug('ExamTypeStrategy: 处理节点', [
                    'node_id' => $nodeId,
                    'node_type' => $node->node_type,
                    'title' => $node->title
                ]);

                // 根据节点类型处理
                switch ($node->node_type) {
                    case 'chapter':
                        // 如果是chapter节点，查找其下的所有section子节点
                        $childNodes = DB::table('textbook_catalog_nodes')
                            ->where('parent_id', $nodeId)
                            ->where('node_type', 'section')
                            ->orderBy('sort_order')
                            ->get();

                        Log::info('ExamTypeStrategy: 解析chapter节点', [
                            'chapter_id' => $nodeId,
                            'chapter_title' => $node->title,
                            'section_count' => count($childNodes)
                        ]);

                        foreach ($childNodes as $child) {
                            if (!in_array($child->id, $finalSectionIds)) {
                                $finalSectionIds[] = $child->id;
                                Log::debug('ExamTypeStrategy: 添加section子节点', [
                                    'parent_chapter' => $nodeId,
                                    'child_node_id' => $child->id,
                                    'child_title' => $child->title,
                                    'child_type' => $child->node_type
                                ]);
                            }
                        }
                        break;

                    case 'section':
                        // 如果是section节点，直接使用
                        if (!in_array($nodeId, $finalSectionIds)) {
                            $finalSectionIds[] = $nodeId;
                            Log::debug('ExamTypeStrategy: 直接使用section节点', [
                                'node_id' => $nodeId,
                                'title' => $node->title,
                                'node_type' => $node->node_type
                            ]);
                        }
                        break;

                    case 'subsection':
                        // 如果是subsection节点，需要找到其父级section节点
                        $parentSection = DB::table('textbook_catalog_nodes')
                            ->where('id', $node->parent_id)
                            ->where('node_type', 'section')
                            ->first();

                        if ($parentSection && !in_array($parentSection->id, $finalSectionIds)) {
                            $finalSectionIds[] = $parentSection->id;
                            Log::debug('ExamTypeStrategy: 通过subsection找到父级section', [
                                'subsection_id' => $nodeId,
                                'subsection_title' => $node->title,
                                'parent_section_id' => $parentSection->id,
                                'parent_section_title' => $parentSection->title
                            ]);
                        }
                        break;

                    default:
                        Log::warning('ExamTypeStrategy: 未知节点类型', [
                            'node_id' => $nodeId,
                            'node_type' => $node->node_type
                        ]);
                        break;
                }
            }

            Log::info('ExamTypeStrategy: 章节节点解析完成', [
                'input_count' => count($chapterIdList),
                'output_section_count' => count($finalSectionIds),
                'section_ids' => $finalSectionIds
            ]);

            return $finalSectionIds;

        } catch (\Exception $e) {
            Log::error('ExamTypeStrategy: 解析章节节点失败', [
                'chapter_id_list' => $chapterIdList,
                'error' => $e->getMessage()
            ]);

            // 出错时返回空数组
            return [];
        }
    }

    // ========== 以下是新增的章节摸底和智能组卷方法 ==========

    /**
     * 章节摸底（新逻辑）
     * - 找第一个未摸底的章节
     * - 用该章节的知识点出题（不扩展子知识点）
     * - 过滤掉没有题目的知识点
     * - 保存时记录 diagnostic_chapter_id
     */
    private function buildChapterDiagnosticParams(array $params): array
    {
        $diagnosticService = app(DiagnosticChapterService::class);
        $textbookId = $params['textbook_id'] ?? null;
        $studentId = (int) ($params['student_id'] ?? 0);
        $grade = $params['grade'] ?? null;
        $totalQuestions = $params['total_questions'] ?? self::defaultTotalQuestions();

        Log::info('ExamTypeStrategy: 构建章节摸底参数', [
            'textbook_id' => $textbookId,
            'student_id' => $studentId,
        ]);

        if (!$textbookId) {
            Log::warning('ExamTypeStrategy: 章节摸底需要 textbook_id 参数');
            return $this->buildGeneralParams($params);
        }

        // 找章节摸底目标：
        // - 传了 chapter_id_list：按指定章节顺序找有题章节（允许重复摸底）
        // - 未传：走默认未摸底优先逻辑
        $chapterInfo = $diagnosticService->getFirstUndiagnosedChapter(
            (int) $textbookId,
            $studentId,
            $params['chapter_id_list'] ?? null
        );

        if (empty($chapterInfo) || empty($chapterInfo['kp_codes'])) {
            Log::warning('ExamTypeStrategy: 章节摸底未找到有效章节', [
                'textbook_id' => $textbookId,
                'student_id' => $studentId,
            ]);
            return $this->buildGeneralParams($params);
        }

        Log::info('ExamTypeStrategy: 章节摸底参数构建完成', [
            'textbook_id' => $textbookId,
            'chapter_id' => $chapterInfo['chapter_id'],
            'chapter_name' => $chapterInfo['chapter_name'] ?? '',
            'section_count' => count($chapterInfo['section_ids'] ?? []),
            'kp_count' => count($chapterInfo['kp_codes']),
            'total_questions' => $totalQuestions,
            'is_restart' => $chapterInfo['is_restart'] ?? false,
        ]);

        $enhanced = array_merge($params, [
            'kp_code_list' => $chapterInfo['kp_codes'],
            'chapter_id_list' => $chapterInfo['section_ids'],
            'diagnostic_chapter_id' => $chapterInfo['chapter_id'], // 记录摸底的章节ID
            'textbook_id' => $textbookId,
            // 注意：不传 grade 参数，禁用"从其他知识点补充"的逻辑
            // 用户需求：题目不够就不够，不从其他知识点补充
            'paper_name' => $params['paper_name'] ?? ('章节摸底_' . ($chapterInfo['chapter_name'] ?? '') . '_' . now()->format('Ymd_His')),
            'assembleType' => 0, // 确保 paper_type 记录为摸底
        ]);

        return $this->buildKnowledgePointAssembleParams($enhanced);
    }

    /**
     * 按知识点顺序学习（新逻辑）
     * - 找当前应该学习的章节（有未达标知识点的章节）
     * - 如果该章节未摸底，返回摸底参数
     * - 按顺序找未达标的知识点，最多2个
     * - 如果都达标，进入下一章摸底
     */
    private function buildChapterIntelligentParams(array $params): array
    {
        $diagnosticService = app(DiagnosticChapterService::class);
        $textbookId = $params['textbook_id'] ?? null;
        $studentId = (int) ($params['student_id'] ?? 0);
        $grade = $params['grade'] ?? null;
        $totalQuestions = $params['total_questions'] ?? self::defaultTotalQuestions();

        Log::info('ExamTypeStrategy: 构建按知识点顺序学习参数', [
            'textbook_id' => $textbookId,
            'student_id' => $studentId,
        ]);

        if (!$textbookId) {
            Log::warning('ExamTypeStrategy: 智能组卷需要 textbook_id 参数');
            return $this->buildGeneralParams($params);
        }

        // 获取当前应该学习的章节
        $chapterInfo = $diagnosticService->getCurrentLearningChapter((int) $textbookId, $studentId, 0.9);

        // 情况1: 所有章节都达标，从第一章重新开始摸底
        if (empty($chapterInfo)) {
            Log::info('ExamTypeStrategy: 所有章节都达标，从第一章重新开始摸底');
            return $this->buildChapterDiagnosticParams($params);
        }

        // 情况2: 当前章节未摸底，需要先摸底
        if (!($chapterInfo['has_diagnostic'] ?? false)) {
            Log::info('ExamTypeStrategy: 当前章节未摸底，先进行摸底', [
                'chapter_id' => $chapterInfo['chapter_id'],
            ]);
            return $this->buildChapterDiagnosticParams($params);
        }

        // 情况3: 已摸底，按顺序找未达标的知识点
        $unmasteredKpCodes = $diagnosticService->getUnmasteredKpCodesInOrder(
            $studentId,
            $chapterInfo['kp_codes'],
            0.9,  // 阈值
            2,    // 最多2个知识点
            $totalQuestions
        );

        // 情况4: 当前章节所有知识点都达标，进入下一章摸底
        if (empty($unmasteredKpCodes)) {
            Log::info('ExamTypeStrategy: 当前章节所有知识点都达标，进入下一章', [
                'current_chapter_id' => $chapterInfo['chapter_id'],
            ]);

            // 获取下一章
            $nextChapter = $diagnosticService->getNextChapter((int) $textbookId, $chapterInfo['chapter_id']);

            if ($nextChapter) {
                // 检查下一章是否已摸底
                $hasNextDiagnostic = $diagnosticService->hasChapterDiagnostic($studentId, $nextChapter['chapter_id']);

                if (!$hasNextDiagnostic) {
                    Log::info('ExamTypeStrategy: 下一章未摸底，进行摸底', [
                        'next_chapter_id' => $nextChapter['chapter_id'],
                    ]);
                    // 直接设置下一章的参数，不递归调用
                    $enhanced = array_merge($params, [
                        'kp_code_list' => $nextChapter['kp_codes'],
                        'chapter_id_list' => $nextChapter['section_ids'],
                        'diagnostic_chapter_id' => $nextChapter['chapter_id'],
                        'textbook_id' => $textbookId,
                        // 注意：不传 grade 参数，禁用"从其他知识点补充"的逻辑
                        'paper_name' => $params['paper_name'] ?? ('章节摸底_' . ($nextChapter['chapter_name'] ?? '') . '_' . now()->format('Ymd_His')),
                        'assembleType' => 0,
                    ]);
                    return $this->buildKnowledgePointAssembleParams($enhanced);
                } else {
                    // 下一章已摸底，找下一章的未达标知识点
                    $nextUnmasteredKpCodes = $diagnosticService->getUnmasteredKpCodesInOrder(
                        $studentId,
                        $nextChapter['kp_codes'],
                        0.9,
                        2,
                        $totalQuestions
                    );

                    if (!empty($nextUnmasteredKpCodes)) {
                        $unmasteredKpCodes = $nextUnmasteredKpCodes;
                        $chapterInfo = $nextChapter;
                    }
                }
            }

            // 如果没有下一章或下一章也都达标，从头开始
            if (empty($unmasteredKpCodes)) {
                Log::info('ExamTypeStrategy: 所有章节都学完，从第一章重新开始');
                return $this->buildChapterDiagnosticParams($params);
            }
        }

        Log::info('ExamTypeStrategy: 按知识点顺序学习参数构建完成', [
            'textbook_id' => $textbookId,
            'chapter_id' => $chapterInfo['chapter_id'],
            'kp_codes' => $unmasteredKpCodes,
            'kp_count' => count($unmasteredKpCodes),
            'total_questions' => $totalQuestions,
        ]);

        $enhanced = array_merge($params, [
            'kp_code_list' => $unmasteredKpCodes,
            'explanation_kp_codes' => $unmasteredKpCodes, // 学案讲解只显示这些知识点（最多2个）
            'textbook_id' => $textbookId,
            // 注意：不传 grade 参数，禁用"从其他知识点补充"的逻辑
            // 用户需求：题目不够就不够，不从其他知识点补充
            'paper_name' => $params['paper_name'] ?? ('智能学习_' . now()->format('Ymd_His')),
            'assembleType' => 1, // paper_type 记录为智能组卷
        ]);

        return $this->buildKnowledgePointAssembleParams($enhanced);
    }
}
