<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use App\Models\KnowledgePoint;
use App\Models\StudentKnowledgeMastery;
use App\Models\TextbookCatalog;
use App\Models\TextbookChapterKnowledgeRelation;

class DiagnosticChapterService
{
    public function getTextbookKnowledgePointsInOrder(int $textbookId): array
    {
        $chapters = TextbookCatalog::query()
            ->where('textbook_id', $textbookId)
            ->where('node_type', 'chapter')
            ->orderBy('sort_order')
            ->orderBy('display_no')
            ->orderBy('id')
            ->get();

        if ($chapters->isEmpty()) {
            Log::warning('DiagnosticChapterService: 未找到章节节点', [
                'textbook_id' => $textbookId,
            ]);
            return [];
        }

        $orderedCodes = [];
        $seen = [];

        foreach ($chapters as $chapter) {
            $sectionIds = TextbookCatalog::query()
                ->where('parent_id', $chapter->id)
                ->where('node_type', 'section')
                ->orderBy('sort_order')
                ->orderBy('display_no')
                ->orderBy('id')
                ->pluck('id')
                ->toArray();

            if (empty($sectionIds)) {
                continue;
            }

            $kpCodes = TextbookChapterKnowledgeRelation::query()
                ->whereIn('catalog_chapter_id', $sectionIds)
                ->where(function ($q) {
                    $q->where('is_deleted', 0)->orWhereNull('is_deleted');
                })
                ->pluck('kp_code')
                ->filter()
                ->unique()
                ->values()
                ->toArray();

            $kpCodes = $this->expandWithChildKnowledgePoints($kpCodes);

            foreach ($kpCodes as $kpCode) {
                if (isset($seen[$kpCode])) {
                    continue;
                }
                $seen[$kpCode] = true;
                $orderedCodes[] = $kpCode;
            }
        }

        Log::info('DiagnosticChapterService: 获取教材知识点顺序列表', [
            'textbook_id' => $textbookId,
            'kp_count' => count($orderedCodes),
        ]);

        return $orderedCodes;
    }

    public function getInitialChapterKnowledgePoints(int $textbookId): array
    {
        $chapter = TextbookCatalog::query()
            ->where('textbook_id', $textbookId)
            ->where('node_type', 'chapter')
            ->orderBy('sort_order')
            ->orderBy('display_no')
            ->orderBy('id')
            ->first();

        if (!$chapter) {
            Log::warning('DiagnosticChapterService: 未找到章节节点', [
                'textbook_id' => $textbookId,
            ]);
            return [];
        }

        $sectionIds = TextbookCatalog::query()
            ->where('parent_id', $chapter->id)
            ->where('node_type', 'section')
            ->orderBy('sort_order')
            ->orderBy('display_no')
            ->orderBy('id')
            ->pluck('id')
            ->toArray();

        if (empty($sectionIds)) {
            Log::warning('DiagnosticChapterService: 章节下未找到section节点', [
                'textbook_id' => $textbookId,
                'chapter_id' => $chapter->id,
            ]);
            return [];
        }

        $kpCodes = TextbookChapterKnowledgeRelation::query()
            ->whereIn('catalog_chapter_id', $sectionIds)
            ->where(function ($q) {
                $q->where('is_deleted', 0)->orWhereNull('is_deleted');
            })
            ->pluck('kp_code')
            ->filter()
            ->unique()
            ->values()
            ->toArray();

        $kpCodes = $this->expandWithChildKnowledgePoints($kpCodes);

        Log::info('DiagnosticChapterService: 获取首章知识点', [
            'textbook_id' => $textbookId,
            'chapter_id' => $chapter->id,
            'section_count' => count($sectionIds),
            'kp_count' => count($kpCodes),
        ]);

        return [
            'chapter_id' => $chapter->id,
            'section_ids' => $sectionIds,
            'kp_codes' => $kpCodes,
        ];
    }

    public function getFirstUnmasteredChapterKnowledgePoints(int $textbookId, int $studentId, float $threshold = 0.9): array
    {
        $chapters = TextbookCatalog::query()
            ->where('textbook_id', $textbookId)
            ->where('node_type', 'chapter')
            ->orderBy('sort_order')
            ->orderBy('display_no')
            ->orderBy('id')
            ->get();

        if ($chapters->isEmpty()) {
            Log::warning('DiagnosticChapterService: 未找到章节节点', [
                'textbook_id' => $textbookId,
            ]);
            return [];
        }

        foreach ($chapters as $chapter) {
            $sectionIds = TextbookCatalog::query()
                ->where('parent_id', $chapter->id)
                ->where('node_type', 'section')
                ->orderBy('sort_order')
                ->orderBy('display_no')
                ->orderBy('id')
                ->pluck('id')
                ->toArray();

            if (empty($sectionIds)) {
                continue;
            }

            $kpCodes = TextbookChapterKnowledgeRelation::query()
                ->whereIn('catalog_chapter_id', $sectionIds)
                ->where(function ($q) {
                    $q->where('is_deleted', 0)->orWhereNull('is_deleted');
                })
                ->pluck('kp_code')
                ->filter()
                ->unique()
                ->values()
                ->toArray();

            $kpCodes = $this->expandWithChildKnowledgePoints($kpCodes);

            if (empty($kpCodes)) {
                continue;
            }

            $allMastered = StudentKnowledgeMastery::allAtLeast($studentId, $kpCodes, $threshold);

            Log::info('DiagnosticChapterService: 章节掌握度评估', [
                'student_id' => $studentId,
                'textbook_id' => $textbookId,
                'chapter_id' => $chapter->id,
                'section_count' => count($sectionIds),
                'kp_count' => count($kpCodes),
                'all_mastered' => $allMastered,
                'threshold' => $threshold,
            ]);

            if (!$allMastered) {
                return [
                    'chapter_id' => $chapter->id,
                    'section_ids' => $sectionIds,
                    'kp_codes' => $kpCodes,
                    'all_mastered' => $allMastered,
                ];
            }
        }

        Log::info('DiagnosticChapterService: 所有章节均达到掌握度阈值', [
            'student_id' => $studentId,
            'textbook_id' => $textbookId,
            'threshold' => $threshold,
        ]);

        return [];
    }

    private function expandWithChildKnowledgePoints(array $kpCodes): array
    {
        if (empty($kpCodes)) {
            return [];
        }

        $baseCodes = collect($kpCodes)->filter()->values()->all();
        $children = KnowledgePoint::query()
            ->whereIn('parent_kp_code', $baseCodes)
            ->orderBy('kp_code')
            ->get(['parent_kp_code', 'kp_code']);

        $childrenMap = [];
        foreach ($children as $child) {
            $childrenMap[$child->parent_kp_code][] = $child->kp_code;
        }

        $ordered = [];
        $seen = [];

        foreach ($baseCodes as $kpCode) {
            if (!isset($seen[$kpCode])) {
                $seen[$kpCode] = true;
                $ordered[] = $kpCode;
            }

            foreach ($childrenMap[$kpCode] ?? [] as $childCode) {
                if (isset($seen[$childCode])) {
                    continue;
                }
                $seen[$childCode] = true;
                $ordered[] = $childCode;
            }
        }

        return $ordered;
    }

    // ========== 以下是新增的方法（不扩展子知识点）==========

    /**
     * 获取章节的知识点（不扩展子知识点）
     * 直接返回 section 绑定的知识点
     */
    public function getChapterKnowledgePointsSimple(int $chapterId): array
    {
        $sectionIds = TextbookCatalog::query()
            ->where('parent_id', $chapterId)
            ->where('node_type', 'section')
            ->orderBy('sort_order')
            ->orderBy('display_no')
            ->orderBy('id')
            ->pluck('id')
            ->toArray();

        if (empty($sectionIds)) {
            return [
                'section_ids' => [],
                'kp_codes' => [],
            ];
        }

        $kpCodes = TextbookChapterKnowledgeRelation::query()
            ->whereIn('catalog_chapter_id', $sectionIds)
            ->where(function ($q) {
                $q->where('is_deleted', 0)->orWhereNull('is_deleted');
            })
            ->pluck('kp_code')
            ->filter()
            ->unique()
            ->values()
            ->toArray();

        // 不扩展子知识点，直接返回
        return [
            'section_ids' => $sectionIds,
            'kp_codes' => $kpCodes,
        ];
    }

    /**
     * 判断章节是否已经摸底过
     */
    public function hasChapterDiagnostic(int $studentId, int $chapterId): bool
    {
        return \App\Models\Paper::query()
            ->where('student_id', (string) $studentId)
            ->where('paper_type', 0) // 摸底类型
            ->where('diagnostic_chapter_id', $chapterId)
            ->exists();
    }

    /**
     * 获取章节摸底目标章节
     * - 传入 targetChapterIds: 先在指定章节内按顺序找第一个未摸底章节；
     *   若指定章节都已摸底，则在该章节所属教材内继续按顺序找未摸底章节。
     * - 未传 targetChapterIds: 保持原逻辑，找教材内第一个未摸底章节。
     */
    public function getFirstUndiagnosedChapter(int $textbookId, int $studentId, ?array $targetChapterIds = null): ?array
    {
        $targetChapterIds = is_array($targetChapterIds)
            ? array_values(array_unique(array_filter(array_map('intval', $targetChapterIds), fn ($id) => $id > 0)))
            : [];
        $payloadCache = [];

        // 指定章节摸底流程：以传入章节为锚点。
        if (!empty($targetChapterIds)) {
            // 兜底：允许传入 section/subsection，自动向上映射到 chapter
            $targetChapterIds = $this->normalizeToChapterIds($targetChapterIds);
            if (empty($targetChapterIds)) {
                Log::warning('DiagnosticChapterService: 指定章节参数无可解析chapter，终止指定章节摸底', [
                    'textbook_id' => $textbookId,
                    'student_id' => $studentId,
                ]);

                return null;
            }

            // 保持传入顺序，首个有效章作为锚点
            $chapterMap = TextbookCatalog::query()
                ->whereIn('id', $targetChapterIds)
                ->where('node_type', 'chapter')
                ->get(['id', 'textbook_id', 'title', 'parent_id', 'node_type', 'sort_order', 'display_no'])
                ->keyBy('id');

            $anchorChapter = null;
            foreach ($targetChapterIds as $chapterId) {
                $candidate = $chapterMap->get($chapterId);
                if ($candidate) {
                    $anchorChapter = $candidate;
                    break;
                }
            }

            if (!$anchorChapter) {
                Log::warning('DiagnosticChapterService: 指定章节未找到有效chapter节点', [
                    'student_id' => $studentId,
                    'target_chapter_ids' => $targetChapterIds,
                ]);
                return null;
            }

            $anchorTextbookId = (int) ($anchorChapter->textbook_id ?? $textbookId);
            $chaptersInTextbook = TextbookCatalog::query()
                ->where('textbook_id', $anchorTextbookId)
                ->where('node_type', 'chapter')
                ->orderBy('sort_order')
                ->orderBy('display_no')
                ->orderBy('id')
                ->get();

            if ($chaptersInTextbook->isEmpty()) {
                Log::warning('DiagnosticChapterService: 指定章节所属教材无章节', [
                    'textbook_id' => $anchorTextbookId,
                    'student_id' => $studentId,
                    'target_chapter_ids' => $targetChapterIds,
                ]);
                return null;
            }

            $chaptersInTextbookIds = $chaptersInTextbook->pluck('id')->map(fn ($id) => (int) $id)->all();
            $diagnosedSet = $this->getDiagnosedChapterIdSet($studentId, $chaptersInTextbookIds);

            // 全教材都摸底：输入什么章就输出什么章（is_restart=true）
            $allDiagnosed = true;
            foreach ($chaptersInTextbookIds as $chapterId) {
                if (!isset($diagnosedSet[$chapterId])) {
                    $allDiagnosed = false;
                    break;
                }
            }

            $anchorPayload = $this->buildChapterPayload((int) $anchorChapter->id, $anchorChapter, $payloadCache);
            if ($allDiagnosed) {
                if ($anchorPayload !== null) {
                    Log::info('DiagnosticChapterService: 全教材已摸底，返回输入锚点章节并重启', [
                        'textbook_id' => $anchorTextbookId,
                        'student_id' => $studentId,
                        'anchor_chapter_id' => $anchorChapter->id,
                    ]);
                    $anchorPayload['is_restart'] = true;
                    return $anchorPayload;
                }

                // 兜底返回教材第一章（is_restart=true）
                $firstChapter = $chaptersInTextbook->first();
                if ($firstChapter) {
                    $firstPayload = $this->buildChapterPayload((int) $firstChapter->id, $firstChapter, $payloadCache);
                    if ($firstPayload !== null) {
                        $firstPayload['is_restart'] = true;
                        Log::info('DiagnosticChapterService: 全教材已摸底且输入章无有效题，兜底第一章重启', [
                            'textbook_id' => $anchorTextbookId,
                            'student_id' => $studentId,
                            'chapter_id' => $firstChapter->id,
                        ]);
                        return $firstPayload;
                    }
                }

                $widePayload = $this->buildTextbookWideChapterPayload($chaptersInTextbook);
                if ($widePayload !== null) {
                    $widePayload['is_restart'] = true;
                    Log::info('DiagnosticChapterService: 全教材已摸底且单章无有效题，合并全教材知识点重启', [
                        'textbook_id' => $anchorTextbookId,
                        'student_id' => $studentId,
                        'diagnostic_chapter_id' => $widePayload['chapter_id'],
                        'kp_count' => count($widePayload['kp_codes']),
                        'section_count' => count($widePayload['section_ids']),
                    ]);

                    return $widePayload;
                }

                return null;
            }

            // 未全教材摸底：优先检查锚点章，未达标就仍以该章摸底
            if ($anchorPayload !== null) {
                $allMastered = StudentKnowledgeMastery::allAtLeastSkipNoQuestions(
                    $studentId,
                    $anchorPayload['kp_codes'],
                    0.9
                );

                if (!$allMastered) {
                    Log::info('DiagnosticChapterService: 锚点章节未达标，继续以该章摸底', [
                        'textbook_id' => $anchorTextbookId,
                        'student_id' => $studentId,
                        'anchor_chapter_id' => $anchorChapter->id,
                        'kp_count' => count($anchorPayload['kp_codes']),
                    ]);
                    return $anchorPayload;
                }
            }

            // 锚点达标后，按教材顺序向后找第一个未摸底章节
            $anchorIndex = $chaptersInTextbook->search(fn ($c) => (int) $c->id === (int) $anchorChapter->id);
            $anchorIndex = $anchorIndex === false ? 0 : (int) $anchorIndex;

            for ($i = $anchorIndex + 1; $i < $chaptersInTextbook->count(); $i++) {
                $chapter = $chaptersInTextbook[$i];
                if (isset($diagnosedSet[(int) $chapter->id])) {
                    continue;
                }
                $payload = $this->buildChapterPayload((int) $chapter->id, $chapter, $payloadCache);
                if ($payload === null) {
                    continue;
                }

                Log::info('DiagnosticChapterService: 锚点章节已达标，向后推进到未摸底章节', [
                    'textbook_id' => $anchorTextbookId,
                    'student_id' => $studentId,
                    'anchor_chapter_id' => $anchorChapter->id,
                    'next_chapter_id' => $chapter->id,
                ]);
                return $payload;
            }

            // 若后续没有可用未摸底章，再从教材起点补找未摸底章
            for ($i = 0; $i <= $anchorIndex; $i++) {
                $chapter = $chaptersInTextbook[$i];
                if (isset($diagnosedSet[(int) $chapter->id])) {
                    continue;
                }
                $payload = $this->buildChapterPayload((int) $chapter->id, $chapter, $payloadCache);
                if ($payload !== null) {
                    Log::info('DiagnosticChapterService: 锚点后无未摸底章，回到教材前序未摸底章节', [
                        'textbook_id' => $anchorTextbookId,
                        'student_id' => $studentId,
                        'anchor_chapter_id' => $anchorChapter->id,
                        'fallback_chapter_id' => $chapter->id,
                    ]);
                    return $payload;
                }
            }

            // 理论兜底：返回输入章并重启
            if ($anchorPayload !== null) {
                $anchorPayload['is_restart'] = true;
                Log::info('DiagnosticChapterService: 指定章节流程兜底返回输入章节重启', [
                    'textbook_id' => $anchorTextbookId,
                    'student_id' => $studentId,
                    'anchor_chapter_id' => $anchorChapter->id,
                ]);
                return $anchorPayload;
            }

            // 未全摸底但锚点无题且后续未摸底章也无题：仍尝试全教材合并（含子知识点扩展）
            $widePayload = $this->buildTextbookWideChapterPayload($chaptersInTextbook);
            if ($widePayload !== null) {
                Log::info('DiagnosticChapterService: 指定章节流程未全摸底但单章无有效题，合并全教材知识点', [
                    'textbook_id' => $anchorTextbookId,
                    'student_id' => $studentId,
                    'anchor_chapter_id' => $anchorChapter->id,
                    'kp_count' => count($widePayload['kp_codes']),
                    'section_count' => count($widePayload['section_ids']),
                ]);

                return $widePayload;
            }

            return null;
        }

        $chapters = TextbookCatalog::query()
            ->where('textbook_id', $textbookId)
            ->where('node_type', 'chapter')
            ->orderBy('sort_order')
            ->orderBy('display_no')
            ->orderBy('id')
            ->get();

        if ($chapters->isEmpty()) {
            return null;
        }

        $chapterIds = $chapters->pluck('id')->map(fn ($id) => (int) $id)->all();
        $diagnosedSet = $this->getDiagnosedChapterIdSet($studentId, $chapterIds);

        foreach ($chapters as $chapter) {
            // 检查是否已摸底
            if (!isset($diagnosedSet[(int) $chapter->id])) {
                $payload = $this->buildChapterPayload((int) $chapter->id, $chapter, $payloadCache);
                if ($payload === null) {
                    // 这个章节没有题目，跳过
                    continue;
                }

                Log::info('DiagnosticChapterService: 找到第一个未摸底的章节', [
                    'textbook_id' => $textbookId,
                    'student_id' => $studentId,
                    'chapter_id' => $chapter->id,
                    'chapter_name' => $chapter->name ?? $chapter->title ?? '',
                    'kp_count' => count($payload['kp_codes']),
                ]);

                return $payload;
            }
        }

        // 所有章节都已摸底，返回第一章（重新开始）
        $firstChapter = $chapters->first();
        $firstPayload = $firstChapter ? $this->buildChapterPayload((int) $firstChapter->id, $firstChapter, $payloadCache) : null;
        if ($firstPayload !== null) {
            Log::info('DiagnosticChapterService: 所有章节都已摸底，返回第一章', [
                'textbook_id' => $textbookId,
                'student_id' => $studentId,
                'chapter_id' => $firstChapter->id,
            ]);
            $firstPayload['is_restart'] = true;

            return $firstPayload;
        }

        $widePayload = $this->buildTextbookWideChapterPayload($chapters);
        if ($widePayload !== null) {
            $widePayload['is_restart'] = true;
            Log::info('DiagnosticChapterService: 所有章节已摸底且第一章无有效题，合并全教材知识点重启', [
                'textbook_id' => $textbookId,
                'student_id' => $studentId,
                'diagnostic_chapter_id' => $widePayload['chapter_id'],
                'kp_count' => count($widePayload['kp_codes']),
                'section_count' => count($widePayload['section_ids']),
            ]);

            return $widePayload;
        }

        return null;
    }

    /**
     * 将传入节点ID（chapter/section/subsection）统一映射为所属 chapter ID 列表。
     * 保持传入顺序去重，忽略不属于当前教材的节点。
     *
     * @param array<int> $nodeIds
     * @return array<int>
     */
    private function normalizeToChapterIds(array $nodeIds): array
    {
        if (empty($nodeIds)) {
            return [];
        }

        $chapterIds = [];
        $seen = [];

        foreach ($nodeIds as $nodeId) {
            $currentId = (int) $nodeId;
            if ($currentId <= 0) {
                continue;
            }

            $guard = 0;
            while ($currentId > 0 && $guard++ < 10) {
                $node = TextbookCatalog::query()
                    ->where('id', $currentId)
                    ->first(['id', 'parent_id', 'node_type']);

                if (!$node) {
                    break;
                }

                if ($node->node_type === 'chapter') {
                    if (!isset($seen[$node->id])) {
                        $seen[$node->id] = true;
                        $chapterIds[] = (int) $node->id;
                    }
                    break;
                }

                $currentId = (int) ($node->parent_id ?? 0);
            }
        }

        if (count($chapterIds) !== count($nodeIds)) {
            Log::info('DiagnosticChapterService: 章节参数已自动映射到chapter节点', [
                'input_ids' => $nodeIds,
                'resolved_chapter_ids' => $chapterIds,
            ]);
        }

        return $chapterIds;
    }

    /**
     * 按教材章节顺序合并全部 section 与知识点，再过滤有题知识点。
     * 用于「全章已摸底」且单章（含第一章）无可用题时的兜底。
     *
     * @param  iterable<int, \App\Models\TextbookCatalog>  $chapters
     */
    private function buildTextbookWideChapterPayload(iterable $chapters): ?array
    {
        $firstChapter = null;
        $allSectionIds = [];
        $seenSection = [];
        $orderedKp = [];
        $seenKp = [];

        foreach ($chapters as $chapter) {
            if ($firstChapter === null) {
                $firstChapter = $chapter;
            }

            $chapterId = (int) $chapter->id;
            $chapterData = $this->getChapterKnowledgePointsSimple($chapterId);

            foreach ($chapterData['section_ids'] as $sid) {
                $sid = (int) $sid;
                if ($sid <= 0 || isset($seenSection[$sid])) {
                    continue;
                }
                $seenSection[$sid] = true;
                $allSectionIds[] = $sid;
            }

            foreach ($chapterData['kp_codes'] as $kpCode) {
                if ($kpCode === null || $kpCode === '') {
                    continue;
                }
                if (isset($seenKp[$kpCode])) {
                    continue;
                }
                $seenKp[$kpCode] = true;
                $orderedKp[] = $kpCode;
            }
        }

        if ($firstChapter === null) {
            return null;
        }

        // 节上多为父知识点编码，题目可能挂在子知识点上；合并兜底时扩展子 KP 再筛有题
        if (!empty($orderedKp)) {
            $orderedKp = $this->expandWithChildKnowledgePoints($orderedKp);
        }

        $kpCodesWithQuestions = $this->filterKpCodesWithQuestions($orderedKp);
        if (empty($kpCodesWithQuestions)) {
            return null;
        }

        return [
            'chapter_id' => (int) $firstChapter->id,
            'chapter_name' => $firstChapter->name ?? $firstChapter->title ?? '',
            'section_ids' => $allSectionIds,
            'kp_codes' => $kpCodesWithQuestions,
        ];
    }

    /**
     * 根据 chapter_id 生成摸底章节载荷，若章节无可用题目知识点则返回 null。
     */
    private function buildChapterPayload(int $chapterId, $chapter = null, ?array &$payloadCache = null): ?array
    {
        if (is_array($payloadCache) && array_key_exists($chapterId, $payloadCache)) {
            return $payloadCache[$chapterId];
        }

        if ($chapter === null) {
            $chapter = TextbookCatalog::query()
                ->where('id', $chapterId)
                ->where('node_type', 'chapter')
                ->first(['id', 'title']);
        }

        if (!$chapter) {
            if (is_array($payloadCache)) {
                $payloadCache[$chapterId] = null;
            }
            return null;
        }

        $chapterData = $this->getChapterKnowledgePointsSimple($chapterId);
        $kpCodesWithQuestions = $this->filterKpCodesWithQuestions($chapterData['kp_codes']);
        if (empty($kpCodesWithQuestions)) {
            if (is_array($payloadCache)) {
                $payloadCache[$chapterId] = null;
            }
            return null;
        }

        $payload = [
            'chapter_id' => $chapterId,
            'chapter_name' => $chapter->name ?? $chapter->title ?? '',
            'section_ids' => $chapterData['section_ids'],
            'kp_codes' => $kpCodesWithQuestions,
        ];
        if (is_array($payloadCache)) {
            $payloadCache[$chapterId] = $payload;
        }

        return $payload;
    }

    /**
     * 批量获取学生在指定章节中的已摸底集合，避免循环 exists N+1 查询。
     *
     * @param array<int> $chapterIds
     * @return array<int, bool>
     */
    private function getDiagnosedChapterIdSet(int $studentId, array $chapterIds): array
    {
        $chapterIds = array_values(array_unique(array_filter(array_map('intval', $chapterIds), fn ($id) => $id > 0)));
        if (empty($chapterIds)) {
            return [];
        }

        // papers.student_id 在模型中为 string，与整型混用可能导致部分环境匹配失败
        $studentKey = (string) $studentId;

        $ids = \App\Models\Paper::query()
            ->where('student_id', $studentKey)
            ->where('paper_type', 0)
            ->whereIn('diagnostic_chapter_id', $chapterIds)
            ->pluck('diagnostic_chapter_id')
            ->map(fn ($id) => (int) $id)
            ->unique()
            ->values()
            ->all();

        $set = [];
        foreach ($ids as $id) {
            $set[$id] = true;
        }

        return $set;
    }

    /**
     * 获取当前应该学习的章节（第一个有未达标知识点的章节）
     * 用于智能组卷流程
     */
    public function getCurrentLearningChapter(int $textbookId, int $studentId, float $threshold = 0.9): ?array
    {
        $chapters = TextbookCatalog::query()
            ->where('textbook_id', $textbookId)
            ->where('node_type', 'chapter')
            ->orderBy('sort_order')
            ->orderBy('display_no')
            ->orderBy('id')
            ->get();

        if ($chapters->isEmpty()) {
            return null;
        }

        foreach ($chapters as $chapter) {
            $chapterData = $this->getChapterKnowledgePointsSimple($chapter->id);
            $kpCodes = $chapterData['kp_codes'];

            if (empty($kpCodes)) {
                continue;
            }

            // 使用新方法判断是否达标（跳过无题知识点）
            $allMastered = StudentKnowledgeMastery::allAtLeastSkipNoQuestions($studentId, $kpCodes, $threshold);

            if (!$allMastered) {
                // 检查是否已摸底
                $hasDiagnostic = $this->hasChapterDiagnostic($studentId, $chapter->id);

                Log::info('DiagnosticChapterService: 找到当前学习章节', [
                    'textbook_id' => $textbookId,
                    'student_id' => $studentId,
                    'student_id_type' => gettype($studentId),
                    'chapter_id' => $chapter->id,
                    'chapter_name' => $chapter->name ?? '',
                    'has_diagnostic' => $hasDiagnostic,
                    'kp_codes' => $kpCodes, // 显示实际的知识点列表
                    'kp_count' => count($kpCodes),
                ]);

                return [
                    'chapter_id' => $chapter->id,
                    'chapter_name' => $chapter->name ?? '',
                    'section_ids' => $chapterData['section_ids'],
                    'kp_codes' => $kpCodes,
                    'has_diagnostic' => $hasDiagnostic,
                ];
            }
        }

        // 所有章节都达标
        Log::info('DiagnosticChapterService: 所有章节都达标', [
            'textbook_id' => $textbookId,
            'student_id' => $studentId,
        ]);

        return null;
    }

    /**
     * 获取下一个章节
     */
    public function getNextChapter(int $textbookId, int $currentChapterId): ?array
    {
        $chapters = TextbookCatalog::query()
            ->where('textbook_id', $textbookId)
            ->where('node_type', 'chapter')
            ->orderBy('sort_order')
            ->orderBy('display_no')
            ->orderBy('id')
            ->get();

        $foundCurrent = false;
        foreach ($chapters as $chapter) {
            if ($foundCurrent) {
                $chapterData = $this->getChapterKnowledgePointsSimple($chapter->id);
                $kpCodesWithQuestions = $this->filterKpCodesWithQuestions($chapterData['kp_codes']);

                if (!empty($kpCodesWithQuestions)) {
                    return [
                        'chapter_id' => $chapter->id,
                        'chapter_name' => $chapter->name ?? '',
                        'section_ids' => $chapterData['section_ids'],
                        'kp_codes' => $kpCodesWithQuestions,
                    ];
                }
            }

            if ($chapter->id === $currentChapterId) {
                $foundCurrent = true;
            }
        }

        return null; // 没有下一章
    }

    /**
     * 过滤出有题目的知识点
     */
    public function filterKpCodesWithQuestions(array $kpCodes): array
    {
        if (empty($kpCodes)) {
            return [];
        }

        $kpCodesWithQuestions = \App\Models\Question::query()
            ->where('audit_status', 0) // 只获取审核通过的题目
            ->whereIn('kp_code', $kpCodes)
            ->distinct()
            ->pluck('kp_code')
            ->toArray();

        // 保持原有顺序
        return array_values(array_intersect($kpCodes, $kpCodesWithQuestions));
    }

    /**
     * 按顺序获取未达标的知识点（用于智能组卷）
     *
     * @param int $studentId 学生ID
     * @param array $kpCodes 知识点列表（按顺序）
     * @param float $threshold 达标阈值
     * @param int $maxCount 最多返回几个知识点
     * @param int $minQuestions 每个知识点最少需要的题目数
     * @return array 未达标的知识点列表
     */
    public function getUnmasteredKpCodesInOrder(
        int $studentId,
        array $kpCodes,
        float $threshold = 0.9,
        int $maxCount = 2,
        int $minQuestions = 20
    ): array {
        if (empty($kpCodes)) {
            return [];
        }

        // 获取掌握度（使用 DB::table 避免 Eloquent accessor 把数字转成文字标签）
        // 【新增】同时获取 direct_mastery_level 和 mastery_level，判断时优先使用 direct_mastery_level
        $masteryRecords = \Illuminate\Support\Facades\DB::table('student_knowledge_mastery')
            ->where('student_id', $studentId)
            ->whereIn('kp_code', $kpCodes)
            ->get(['kp_code', 'mastery_level', 'direct_mastery_level'])
            ->keyBy('kp_code');

        // 构建有效掌握度映射：取 direct_mastery_level 和 mastery_level 的最大值
        // 避免"学了之后反而从达标变成未达标"的问题
        $levels = [];
        foreach ($masteryRecords as $kpCode => $record) {
            $direct = $record->direct_mastery_level;
            $mastery = (float) $record->mastery_level;

            if ($direct !== null) {
                // 取两者最大值：直接学习达标或聚合值达标，都算达标
                $levels[$kpCode] = max((float) $direct, $mastery);
            } else {
                $levels[$kpCode] = $mastery;
            }
        }

        // 【调试】记录查询到的掌握度
        Log::info('DiagnosticChapterService: 查询掌握度结果', [
            'student_id' => $studentId,
            'student_id_type' => gettype($studentId),
            'input_kp_codes' => $kpCodes,
            'found_levels' => $levels,
            'raw_records' => $masteryRecords->toArray(),
        ]);

        // 获取每个知识点的题目数量（只统计审核通过的题目）
        $questionCounts = \App\Models\Question::query()
            ->where('audit_status', 0) // 只获取审核通过的题目
            ->whereIn('kp_code', $kpCodes)
            ->selectRaw('kp_code, COUNT(*) as count')
            ->groupBy('kp_code')
            ->pluck('count', 'kp_code')
            ->toArray();

        $result = [];
        $totalQuestions = 0;

        foreach ($kpCodes as $kpCode) {
            // 跳过没有题目的知识点
            $count = $questionCounts[$kpCode] ?? 0;
            if ($count === 0) {
                continue;
            }

            // 检查是否达标
            $level = isset($levels[$kpCode]) ? (float) $levels[$kpCode] : 0.0;
            $isMastered = $level >= $threshold;
            Log::info("DiagnosticChapterService: 检查知识点", [
                'kp_code' => $kpCode,
                'level' => $level,
                'threshold' => $threshold,
                'is_mastered' => $isMastered,
                'level_found_in_db' => isset($levels[$kpCode]),
            ]);
            if ($level >= $threshold) {
                continue;
            }

            // 添加到结果
            $result[] = $kpCode;
            $totalQuestions += $count;

            // 检查是否达到最大数量
            if (count($result) >= $maxCount) {
                break;
            }

            // 检查题目数量是否足够
            if ($totalQuestions >= $minQuestions) {
                break;
            }
        }

        Log::info('DiagnosticChapterService: 获取未达标知识点', [
            'student_id' => $studentId,
            'input_kp_codes' => $kpCodes,
            'result_kp_codes' => $result,
            'levels_found' => $levels,
            'total_questions' => $totalQuestions,
            'threshold' => $threshold,
        ]);

        return $result;
    }
}
