<?php

namespace App\Jobs;

use App\Models\OCRRecord;
use App\Services\OCRProcessingService;
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 ProcessOCRSubmission 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(OCRProcessingService $ocrService): void
    {
        $ocrRecord = OCRRecord::find($this->ocrRecordId);

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

        try {
            Log::info('开始处理OCR任务', ['ocr_record_id' => $this->ocrRecordId]);

            // 更新状态为处理中
            $ocrRecord->update(['status' => 'processing']);

            // 调用OCR服务 - 通过paper_title查找关联的试卷
            $paperId = null;
            if ($ocrRecord->paper_title) {
                $paper = \App\Models\Paper::where('paper_name', $ocrRecord->paper_title)->first();
                $paperId = $paper?->paper_id ?? $paper?->id;
            }
            $results = $ocrService->processImage($ocrRecord->file_path, $paperId);

            // 保存OCR结果到数据库
            foreach ($results['answers'] as $answer) {
                \App\Models\OCRQuestionResult::create([
                    'ocr_record_id' => $this->ocrRecordId,
                    'question_number' => $answer['q'],
                    'question_type' => $answer['type'],
                    'student_answer' => $answer['value'],
                    'answer_confidence' => $answer['confidence'] ?? 0.9,
                    'generation_status' => 'completed',
                ]);
            }

            // 更新OCR记录状态
            $ocrRecord->update([
                'status' => 'completed',
                'total_questions' => count($results['answers']),
            ]);

            Log::info('OCR处理完成', [
                'ocr_record_id' => $this->ocrRecordId,
                'question_count' => count($results['answers']),
            ]);

            // 触发AI判分任务
            \App\Jobs\AIGradingJob::dispatch($this->ocrRecordId);

        } catch (\Exception $e) {
            Log::error('OCR处理失败', [
                'ocr_record_id' => $this->ocrRecordId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            $ocrRecord->update([
                'status' => 'failed',
                'error_message' => $e->getMessage(),
            ]);

            throw $e;
        }
    }
}
