<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class OCRQuestionResult extends Model
{
    use HasFactory;

    protected $table = 'ocr_question_results';

    public $timestamps = false;

    protected $fillable = [
        'ocr_record_id',
        'question_number',
        'kp_code',
        'skill_ids',
        'score_area_text',
        'score_area_bbox',
        'score_value',
        'score_confidence',
        'mark_detected',
        'mark_confidence',
        'student_answer',
        'manual_answer',
        'answer_verified',
        'student_answer_bbox',
        'answer_confidence',
        'answer_area_crop_path',
        'question_text',
        'question_bbox',
        'ai_score',
        'ai_feedback',
        'ai_confidence',
        'ai_analysis_method',
        'ai_analyzed_at',
        'question_bank_id',
        'generation_status',
        'generation_task_id',
        'generation_error',
    ];

    protected $casts = [
        'skill_ids' => 'array',
        'score_area_bbox' => 'array',
        'ai_score' => 'float',
        'mark_confidence' => 'float',
        'student_answer_bbox' => 'array',
        'answer_confidence' => 'float',
        'question_bbox' => 'array',
        'ai_confidence' => 'float',
        'ai_analyzed_at' => 'datetime',
    ];

    public function ocrRecord(): BelongsTo
    {
        return $this->belongsTo(OCRRecord::class, 'ocr_record_id', 'id');
    }

    public function getMarkBadgeAttribute(): string
    {
        if (!$this->mark_detected) {
            return '<span class="px-2 py-1 text-xs rounded bg-gray-100 text-gray-800">未识别</span>';
        }

        return match ($this->mark_detected) {
            '✓', '√', '✔', 'correct' => '<span class="px-2 py-1 text-xs rounded bg-green-100 text-green-800">正确 ✓</span>',
            '✗', '×', '❌', 'wrong' => '<span class="px-2 py-1 text-xs rounded bg-red-100 text-red-800">错误 ✗</span>',
            default => '<span class="px-2 py-1 text-xs rounded bg-yellow-100 text-yellow-800">' . $this->mark_detected . '</span>',
        };
    }

    public function getConfidenceColorAttribute(): string
    {
        $confidence = $this->score_confidence ?? 0;
        return match (true) {
            $confidence >= 0.8 => 'text-green-600',
            $confidence >= 0.6 => 'text-yellow-600',
            $confidence >= 0.4 => 'text-orange-600',
            default => 'text-red-600',
        };
    }

    public function getAnswerAreaCropUrlAttribute(): string
    {
        if ($this->answer_area_crop_path && file_exists(public_path($this->answer_area_crop_path))) {
            return asset($this->answer_area_crop_path);
        }
        return '';
    }
}
