<?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;
    }

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

            $taskManager->updateTaskProgress($this->taskId, 10, '开始生成试卷PDF...');

            // 生成试卷PDF
            $pdfUrl = $pdfExportService->generateExamPdf($this->paperId)
                ?? $questionBankService->exportExamToPdf($this->paperId)
                ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $this->paperId, 'answer' => 'false']);

            $taskManager->updateTaskProgress($this->taskId, 50, '试卷PDF生成完成，开始生成判卷PDF...');

            // 生成判卷PDF
            $gradingPdfUrl = $pdfExportService->generateGradingPdf($this->paperId)
                ?? route('filament.admin.auth.intelligent-exam.pdf', ['paper_id' => $this->paperId, 'answer' => 'true']);

            // 构建完整的试卷内容
            $paperModel = Paper::with('questions')->find($this->paperId);
            $examContent = $paperModel
                ? $paperPayloadService->buildExamContent($paperModel)
                : [];

            // 标记任务完成
            $taskManager->markTaskCompleted($this->taskId, [
                'exam_content' => $examContent,
                'pdfs' => [
                    'exam_paper_pdf' => $pdfUrl,
                    'grading_pdf' => $gradingPdfUrl,
                ],
            ]);

            Log::info('PDF生成队列任务完成', [
                'task_id' => $this->taskId,
                'paper_id' => $this->paperId,
                'pdf_url' => $pdfUrl,
                'grading_pdf_url' => $gradingPdfUrl,
            ]);

            // 发送回调通知
            $taskManager->sendCallback($this->taskId);

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

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