<?php

namespace App\Jobs;

use App\Models\OCRRecord;
use App\Services\IntelligentGradingService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class RegradeOCRSubmission implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $ocrRecordId;
    public int $maxAttempts = 3;

    public function __construct(int $ocrRecordId)
    {
        $this->ocrRecordId = $ocrRecordId;
    }

    public function handle(IntelligentGradingService $gradingService): void
    {
        $ocrRecord = OCRRecord::find($this->ocrRecordId);

        if (!$ocrRecord) {
            Log::error('OCR记录不存在，无法重新判分', ['ocr_record_id' => $this->ocrRecordId]);
            return;
        }

        try {
            Log::info('开始重新判分任务', ['ocr_record_id' => $this->ocrRecordId]);

            // 清除之前的AI判分结果
            \App\Models\OCRQuestionResult::where('ocr_record_id', $this->ocrRecordId)
                ->update([
                    'ai_score' => null,
                    'ai_feedback' => null,
                    'ai_confidence' => null,
                    'ai_analyzed_at' => null,
                ]);

            // 重新调用判分服务
            $results = $gradingService->gradeSubmission($this->ocrRecordId);

            Log::info('重新判分完成', [
                'ocr_record_id' => $this->ocrRecordId,
                'total_score' => $results['total_score'] ?? 0,
            ]);

        } catch (\Exception $e) {
            Log::error('重新判分失败', [
                'ocr_record_id' => $this->ocrRecordId,
                'error' => $e->getMessage(),
            ]);

            throw $e;
        }
    }
}
