<?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\DB;
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 {
            // 从 exam_analysis_results 表查询PDF URL
            $report = DB::table('exam_analysis_results')
                ->where('paper_id', $paperId)
                ->first();

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

                return response()->json([
                    'success' => true,
                    'data' => [
                        'paper_id' => $paperId,
                        'status' => 'completed',
                        'pdf_url' => $report->analysis_pdf_url,
                        'message' => '报告已生成',
                        'generated_at' => $report->created_at ?? null,
                    ]
                ], 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;
        }
    }
}
