<?php

namespace App\DTO;

/**
 * 报告负载数据传输对象
 * 用于PDF生成时的数据封装
 */
class ReportPayloadDto
{
    public function __construct(
        public readonly array $paper,
        public readonly array $student,
        public readonly array $teacher,
        public readonly array $questions,
        public readonly array $mastery,
        public readonly array $examHitKpCodes,
        public readonly array $parentMasteryLevels, // 新增：父节点掌握度数据
        public readonly array $questionInsights,
        public readonly array $recommendations,
        public readonly array $analysisData = []
    ) {}

    /**
     * 从ExamAnalysisDataDto创建
     */
    public static function fromExamAnalysisDataDto(ExamAnalysisDataDto $dto): self
    {
        return new self(
            paper: $dto->paper,
            student: $dto->student,
            teacher: $dto->teacher,
            questions: $dto->questions,
            mastery: $dto->mastery,
            examHitKpCodes: $dto->examHitKpCodes,
            parentMasteryLevels: $dto->parentMasteryLevels, // 新增：父节点掌握度数据
            questionInsights: $dto->insights,
            recommendations: $dto->recommendations,
            // 必须透传原始 analysis_data，模板依赖 question_analysis/knowledge_point_analysis 原始结构
            analysisData: $dto->rawAnalysisData
        );
    }

    /**
     * 转换为数组
     */
    public function toArray(): array
    {
        return [
            'paper' => $this->paper,
            'student' => $this->student,
            'teacher' => $this->teacher,
            'questions' => $this->questions,
            'mastery' => $this->mastery,
            'exam_hit_kp_codes' => $this->examHitKpCodes,
            'parent_mastery_levels' => $this->parentMasteryLevels, // 新增：父节点掌握度数据
            'question_insights' => $this->questionInsights,
            'recommendations' => $this->recommendations,
            'analysis_data' => $this->analysisData,
        ];
    }

    /**
     * 按题型分组题目
     */
    public function getQuestionsByType(): array
    {
        $grouped = [
            'choice' => [],
            'fill' => [],
            'answer' => [],
        ];

        foreach ($this->questions as $question) {
            $type = $question['question_type'] ?? 'answer';
            $normalizedType = $this->normalizeQuestionType($type);
            $grouped[$normalizedType][] = $question;
        }

        return $grouped;
    }

    /**
     * 标准化题型名称
     */
    private function normalizeQuestionType(string $type): string
    {
        $t = strtolower(trim($type));
        return match (true) {
            str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
            str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
            default => 'answer',
        };
    }

    /**
     * 获取按卷面顺序排列的题目
     */
    public function getOrderedQuestions(): array
    {
        $grouped = $this->getQuestionsByType();
        $ordered = array_merge($grouped['choice'], $grouped['fill'], $grouped['answer']);

        // 添加显示序号
        foreach ($ordered as $i => &$question) {
            $question['display_number'] = $i + 1;
        }
        unset($question);

        return $ordered;
    }

    /**
     * 获取知识点名称映射
     */
    public function getKnowledgePointNameMap(): array
    {
        $map = [];
        foreach ($this->questions as $question) {
            $kpCode = $question['knowledge_point'] ?? $question['kp_code'] ?? '';
            $kpName = $question['knowledge_point_name'] ?? $kpCode;
            if ($kpCode && $kpName) {
                $map[$kpCode] = $kpName;
            }
        }
        return $map;
    }
}
