<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\ExamAnalysisService;
use App\Services\TaskManager;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ExamAnalysisApiController extends Controller
{
    public function __construct(
        private readonly ExamAnalysisService $examAnalysisService,
        private readonly TaskManager $taskManager
    ) {}

    /**
     * 生成学情报告（异步模式）
     * 立即返回任务ID，PDF生成在后台进行
     */
    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'paper_id' => 'required|string',
            'student_id' => 'nullable|string',
            'record_id' => 'nullable|string',
            'callback_url' => 'nullable|url',
        ]);

        $paperId = $data['paper_id'];
        $studentId = $data['student_id'] ?? null;
        $recordId = $data['record_id'] ?? null;

        try {
            // 如果没有提供student_id，尝试从paper_id获取
            if (!$studentId) {
                $studentId = $this->getStudentIdFromPaper($paperId);
            }

            if (!$studentId) {
                return response()->json([
                    'success' => false,
                    'message' => '缺少 student_id',
                ], 422);
            }

            // 使用ExamAnalysisService生成报告
            $taskId = $this->examAnalysisService->generateReport($paperId, $studentId, $recordId);

            // 构建返回数据
            $payload = [
                'success' => true,
                'message' => '学情报告任务已创建，正在后台生成PDF...',
                'data' => [
                    'task_id' => $taskId,
                    'paper_id' => $paperId,
                    'student_id' => $studentId,
                    'record_id' => $recordId,
                    'status' => 'processing',
                    'analysis_url' => route('filament.admin.pages.exam-analysis', [
                        'paperId' => $paperId,
                        'studentId' => $studentId,
                        'recordId' => $recordId,
                    ]),
                    'pdf_url' => null,  // 稍后生成
                    'created_at' => now()->toISOString(),
                ],
            ];

            return response()->json($payload, 200, [], JSON_UNESCAPED_SLASHES);

        } catch (\Exception $e) {
            Log::error('学情报告API失败', [
                'paper_id' => $paperId,
                'student_id' => $studentId,
                'record_id' => $recordId,
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'message' => '服务异常：' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * 轮询任务状态
     */
    public function status(string $taskId): JsonResponse
    {
        try {
            $task = $this->taskManager->getTaskStatus($taskId);

            if (!$task) {
                return response()->json([
                    'success' => false,
                    'message' => '任务不存在',
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $task,
            ]);

        } catch (\Exception $e) {
            Log::error('查询学情报告任务状态失败', [
                'task_id' => $taskId,
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'message' => '查询失败：' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * 获取PDF报告URL
     * 查询指定试卷是否已有生成好的学情分析报告
     */
    public function getPdfUrl(string $paperId): JsonResponse
    {
        try {
            // 首先尝试从 student_reports 表直接查询（最快速的方式）
            $report = \App\Models\StudentReport::where('paper_id', $paperId)
                ->where('report_type', 'exam_analysis')
                ->first();

            if ($report && $report->pdf_url && $report->generation_status === 'completed') {
                Log::info('学情报告PDF URL查询成功（从数据库）', [
                    'paper_id' => $paperId,
                    'pdf_url' => $report->pdf_url,
                ]);

                return response()->json([
                    'success' => true,
                    'data' => [
                        'paper_id' => $paperId,
                        'status' => 'completed',
                        'pdf_url' => $report->pdf_url,
                        'message' => '报告已生成',
                        'generated_at' => $report->generated_at?->toISOString(),
                    ]
                ], 200, [], JSON_UNESCAPED_SLASHES);
            }

            // 如果数据库中没有，尝试从任务系统查找
            $task = $this->taskManager->findAnalysisTaskByPaperId($paperId);

            if ($task) {
                $status = $task['status'];
                $pdfUrl = $task['pdf_url'] ?? null;

                if ($status === \App\Services\TaskManager::STATUS_COMPLETED && $pdfUrl) {
                    // 任务已完成且有PDF URL
                    Log::info('学情报告PDF URL查询成功（从任务系统）', [
                        'paper_id' => $paperId,
                        'task_id' => $task['task_id'],
                        'pdf_url' => $pdfUrl,
                    ]);

                    return response()->json([
                        'success' => true,
                        'data' => [
                            'paper_id' => $paperId,
                            'status' => 'completed',
                            'pdf_url' => $pdfUrl,
                            'message' => '报告已生成',
                            'generated_at' => $task['completed_at'] ?? null,
                        ]
                    ], 200, [], JSON_UNESCAPED_SLASHES);
                } elseif ($status === \App\Services\TaskManager::STATUS_PROCESSING) {
                    // 任务正在处理中
                    Log::info('学情报告正在生成中', [
                        'paper_id' => $paperId,
                        'task_id' => $task['task_id'],
                        'progress' => $task['progress'] ?? 0,
                    ]);

                    return response()->json([
                        'success' => true,
                        'data' => [
                            'paper_id' => $paperId,
                            'status' => 'processing',
                            'pdf_url' => null,
                            'message' => '报告正在生成中，请稍后刷新页面查看',
                            'progress' => $task['progress'] ?? 0,
                        ]
                    ], 200, [], JSON_UNESCAPED_SLASHES);
                } elseif ($status === \App\Services\TaskManager::STATUS_FAILED) {
                    // 任务失败
                    Log::warning('学情报告生成失败', [
                        'paper_id' => $paperId,
                        'task_id' => $task['task_id'],
                        'error' => $task['error'] ?? '未知错误',
                    ]);

                    return response()->json([
                        'success' => false,
                        'data' => [
                            'paper_id' => $paperId,
                            'status' => 'failed',
                            'pdf_url' => null,
                            'message' => '报告生成失败：' . ($task['error'] ?? '未知错误'),
                        ]
                    ], 200, [], JSON_UNESCAPED_SLASHES);
                }
            }

            // 既没有完成的任务，也没有正在进行的任务
            Log::info('未找到学情报告任务', ['paper_id' => $paperId]);

            return response()->json([
                'success' => true,
                'data' => [
                    'paper_id' => $paperId,
                    'status' => 'not_found',
                    'pdf_url' => null,
                    'message' => '报告尚未生成，请先提交试卷进行分析',
                ]
            ], 200, [], JSON_UNESCAPED_SLASHES);

        } catch (\Exception $e) {
            Log::error('查询学情报告PDF URL失败', [
                'paper_id' => $paperId,
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'message' => '查询失败：' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * 从试卷ID获取学生ID
     */
    private function getStudentIdFromPaper(string $paperId): ?string
    {
        try {
            $paper = \App\Models\Paper::find($paperId);
            return $paper?->student_id;
        } catch (\Exception $e) {
            Log::warning('获取试卷学生ID失败', [
                'paper_id' => $paperId,
                'error' => $e->getMessage(),
            ]);
            return null;
        }
    }
}
