<?php

namespace App\Jobs;

use App\Models\Paper;
use App\Services\ExamPdfExportService;
use App\Services\QuestionBankService;
use App\Services\PaperPayloadService;
use App\Services\TaskManager;
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 GenerateExamPdfJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public string $taskId;
    public string $paperId;
    public int $maxAttempts = 3;

    public function __construct(string $taskId, string $paperId)
    {
        $this->taskId = $taskId;
        $this->paperId = $paperId;

        // 指定使用 pdf 队列，由独立的 pdf-worker 容器处理
        $this->onQueue('pdf');
    }

    public function handle(
        ExamPdfExportService $pdfExportService,
        QuestionBankService $questionBankService,
        PaperPayloadService $paperPayloadService,
        TaskManager $taskManager
    ): void {
        try {
            Log::info('开始处理PDF生成队列任务', [
                'task_id' => $this->taskId,
                'paper_id' => $this->paperId,
                'attempt' => $this->attempts(),
            ]);

            // 【修复】首先检查试卷是否存在
            $paperModel = Paper::with('questions')->find($this->paperId);
            if (!$paperModel) {
                Log::error('PDF生成队列任务失败：试卷不存在', [
                    'task_id' => $this->taskId,
                    'paper_id' => $this->paperId,
                    'attempt' => $this->attempts(),
                ]);

                // 如果试卷不存在，判断是否需要重试
                if ($this->attempts() < $this->maxAttempts) {
                    Log::info('试卷不存在，将在2秒后重试', [
                        'task_id' => $this->taskId,
                        'paper_id' => $this->paperId,
                        'attempt' => $this->attempts(),
                        'next_attempt' => $this->attempts() + 1,
                    ]);
                    // 延迟2秒后重试（缩短间隔，减少对回调的影响）
                    $this->release(2);
                    return;
                } else {
                    Log::error('试卷不存在且已达到最大重试次数，标记任务失败', [
                        'task_id' => $this->taskId,
                        'paper_id' => $this->paperId,
                        'attempts' => $this->attempts(),
                    ]);
                    $taskManager->markTaskFailed($this->taskId, "试卷不存在: {$this->paperId}");
                    return;
                }
            }

            // 检查试卷是否有题目
            if ($paperModel->questions->isEmpty()) {
                Log::error('PDF生成队列任务失败：试卷没有题目数据', [
                    'task_id' => $this->taskId,
                    'paper_id' => $this->paperId,
                    'question_count' => 0,
                ]);

                if ($this->attempts() < $this->maxAttempts) {
                    Log::info('试卷没有题目，将在1秒后重试', [
                        'task_id' => $this->taskId,
                        'paper_id' => $this->paperId,
                        'attempt' => $this->attempts(),
                    ]);
                    // 延迟1秒后重试（更短间隔）
                    $this->release(1);
                    return;
                } else {
                    $taskManager->markTaskFailed($this->taskId, "试卷没有题目数据: {$this->paperId}");
                    return;
                }
            }

            $taskManager->updateTaskProgress($this->taskId, 10, '开始生成统一PDF（直接合并两个页面，效率最高）...');

            // 【终极优化】直接合并两个HTML页面生成一份PDF（无需生成单独PDF）
            $unifiedPdfUrl = $pdfExportService->generateUnifiedPdf($this->paperId);

            $taskManager->updateTaskProgress($this->taskId, 90, 'PDF生成完成，准备返回结果...');
            $examContent = $paperPayloadService->buildExamContent($paperModel);

            // 标记任务完成（完整PDF存储到all_pdf_url字段）
            $taskManager->markTaskCompleted($this->taskId, [
                'exam_content' => $examContent,
                'pdfs' => [
                    'all_pdf' => $unifiedPdfUrl, // 【完整PDF】包含试卷和判卷，存储到all_pdf_url字段
                ],
            ]);

            Log::info('PDF生成队列任务完成（终极优化：直接合并HTML生成一份完整PDF）', [
                'task_id' => $this->taskId,
                'paper_id' => $this->paperId,
                'all_pdf_url' => $unifiedPdfUrl,
                'question_count' => $paperModel->questions->count(),
                'method' => 'generateUnifiedPdf (direct merge, fastest)',
            ]);

            // 发送回调通知（在合并PDF完成后）
            $taskManager->sendCallback($this->taskId);

        } catch (\Exception $e) {
            Log::error('PDF生成队列任务失败', [
                'task_id' => $this->taskId,
                'paper_id' => $this->paperId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            // 如果是第一次失败且试卷可能还在创建中，等待后重试
            if ($this->attempts() < $this->maxAttempts && strpos($e->getMessage(), '不存在') !== false) {
                Log::info('检测到试卷不存在错误，将在2秒后重试', [
                    'task_id' => $this->taskId,
                    'paper_id' => $this->paperId,
                    'attempt' => $this->attempts(),
                ]);
                $this->release(2);
                return;
            }

            $taskManager->markTaskFailed($this->taskId, $e->getMessage());
        }
    }
}
