<?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 AIGradingJob 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记录不存在，无法进行AI判分', ['ocr_record_id' => $this->ocrRecordId]);
            return;
        }

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

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

            Log::info('AI判分任务完成', [
                'ocr_record_id' => $this->ocrRecordId,
                'total_score' => $results['total_score'] ?? 0,
                'method' => $results['method'] ?? 'api',
            ]);

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

            throw $e;
        }
    }
}
