<?php

namespace App\Jobs;

use App\Models\OCRRecord;
use App\Services\OCRService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;

class ProcessOCRRecord implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;
    public int $timeout = 300;

    protected int $recordId;

    /**
     * Create a new job instance.
     */
    public function __construct(int $recordId)
    {
        $this->recordId = $recordId;
    }

    /**
     * Execute the job.
     */
    public function handle(\App\Services\OCRService $ocrService): void
    {
        $record = OCRRecord::find($this->recordId);

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

        if ($record->status === 'completed') {
            Log::info('OCR记录已处理完成，跳过', ['record_id' => $this->recordId]);
            return;
        }

        Log::info('OCR: 开始处理任务', [
            'record_id' => $this->recordId,
            'paper_title' => $record->paper_title,
            'file_path' => $record->file_path,
            'student_id' => $record->student_id,
            'analysis_id' => $record->analysis_id
        ]);

        try {
            // 使用本地OCR服务处理
            $ocrService->reprocess($record);

            Log::info('OCR处理任务已完成', ['record_id' => $this->recordId]);

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

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

            throw $e;
        }
    }

    /**
     * Handle a job failure.
     */
    public function failed(\Throwable $exception): void
    {
        $record = OCRRecord::find($this->recordId);

        if ($record) {
            $record->update([
                'status' => 'failed',
                'error_message' => '处理失败: ' . $exception->getMessage(),
            ]);
        }

        Log::error('OCR处理Job失败', [
            'record_id' => $this->recordId,
            'error' => $exception->getMessage(),
        ]);
    }
}
