<?php

namespace App\Models;

use App\Services\MathFormulaProcessor;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class StudentExercise extends Model
{
    use HasFactory;

    protected $fillable = [
        'student_id',
        'question_id',
        'knowledge_point_id',
        'question_content',
        'student_answer',
        'correct_answer',
        'is_correct',
        'submission_status',
        'batch_id',
        'kp_code',
        'selected_skills',
        'skill_scores',
        'time_spent_seconds',
        'difficulty_level',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'is_correct' => 'boolean',
        'knowledge_point_id' => 'integer',
        'selected_skills' => 'array',
        'skill_scores' => 'array',
        'time_spent_seconds' => 'integer',
        'difficulty_level' => 'float',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * 获取处理后的题目内容（包含数学公式处理）
     */
    public function getProcessedQuestionContentAttribute(): string
    {
        return MathFormulaProcessor::processFormulas($this->question_content ?? '');
    }

    /**
     * 获取处理后的学生答案（包含数学公式处理）
     */
    public function getProcessedStudentAnswerAttribute(): string
    {
        return MathFormulaProcessor::processFormulas($this->student_answer ?? '');
    }

    /**
     * 获取处理后的正确答案（包含数学公式处理）
     */
    public function getProcessedCorrectAnswerAttribute(): string
    {
        return MathFormulaProcessor::processFormulas($this->correct_answer ?? '');
    }

    /**
     * 获取处理后的数据数组（用于API返回）
     */
    public function toProcessedArray(): array
    {
        $data = $this->toArray();

        // 处理数学公式字段
        $mathFields = ['question_content', 'student_answer', 'correct_answer'];

        foreach ($mathFields as $field) {
            if (isset($data[$field]) && is_string($data[$field])) {
                $data[$field] = MathFormulaProcessor::processFormulas($data[$field]);
            }
        }

        return $data;
    }
}