<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\MathRecSysService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class StudentController extends Controller
{
    protected MathRecSysService $mathRecSys;

    public function __construct(MathRecSysService $mathRecSys)
    {
        $this->mathRecSys = $mathRecSys;
    }

    /**
     * 获取学生完整信息（集成MathRecSys数据）
     *
     * @param string $studentId 学生ID
     * @return JsonResponse
     */
    public function show(string $studentId): JsonResponse
    {
        try {
            // 获取Laravel本地数据
            $localStudent = $this->getLocalStudent($studentId);

            // 获取MathRecSys能力画像
            $mathRecSysProfile = $this->mathRecSys->getStudentProfile($studentId);

            // 获取薄弱知识点
            $weakPoints = $this->mathRecSys->getWeakPoints($studentId);

            // 合并数据
            $studentData = [
                'basic_info' => $localStudent,
                'ability_profile' => $mathRecSysProfile['data'] ?? [],
                'mastery_levels' => $this->formatMasteryLevels($mathRecSysProfile),
                'weak_points' => $weakPoints['data'] ?? [],
                'learning_progress' => $mathRecSysProfile['progress'] ?? [],
                'recommendations' => $this->getStudentRecommendations($studentId),
                'last_updated' => now()->toISOString()
            ];

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

        } catch (\Exception $e) {
            \Log::error('获取学生信息失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => '获取学生信息失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取班级整体分析
     *
     * @param string $classId 班级ID
     * @return JsonResponse
     */
    public function classAnalysis(string $classId): JsonResponse
    {
        try {
            $analysis = $this->mathRecSys->getClassAnalysis($classId);

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

        } catch (\Exception $e) {
            \Log::error('获取班级分析失败', [
                'class_id' => $classId,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => '获取班级分析失败'
            ], 500);
        }
    }

    /**
     * 获取学生个性化推荐
     *
     * @param string $studentId 学生ID
     * @param Request $request
     * @return JsonResponse
     */
    public function getRecommendations(string $studentId, Request $request): JsonResponse
    {
        try {
            $options = $request->only(['count', 'difficulty', 'focus_kp']);
            $recommendations = $this->mathRecSys->getRecommendations($studentId, $options);

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

        } catch (\Exception $e) {
            \Log::error('获取推荐失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => '获取推荐失败'
            ], 500);
        }
    }

    /**
     * 智能分析题目
     *
     * @param Request $request
     * @param string $studentId 学生ID
     * @return JsonResponse
     */
    public function analyzeQuestion(Request $request, string $studentId): JsonResponse
    {
        $request->validate([
            'question' => 'required|string',
            'student_answer' => 'required|string',
            'correct_answer' => 'required|string',
            'focus_kp' => 'nullable|string',
            'question_type' => 'nullable|string',
            'difficulty' => 'nullable|numeric|min:0|max:1',
        ]);

        try {
            $analysisData = [
                'student_id' => $studentId,
                'question' => $request->question,
                'student_answer' => $request->student_answer,
                'correct_answer' => $request->correct_answer,
                'focus_kp' => $request->focus_kp,
                'question_type' => $request->question_type ?? '计算题',
                'difficulty' => $request->difficulty ?? 0.5,
            ];

            $analysis = $this->mathRecSys->smartAnalyze($analysisData);

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

        } catch (\Exception $e) {
            \Log::error('题目分析失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => '题目分析失败'
            ], 500);
        }
    }

    /**
     * 获取学习轨迹
     *
     * @param string $studentId 学生ID
     * @param Request $request
     * @return JsonResponse
     */
    public function getTrajectory(string $studentId, Request $request): JsonResponse
    {
        try {
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $trajectory = $this->mathRecSys->getLearningTrajectory($studentId, $startDate, $endDate);

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

        } catch (\Exception $e) {
            \Log::error('获取学习轨迹失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => '获取学习轨迹失败'
            ], 500);
        }
    }

    /**
     * 获取学习建议
     *
     * @param string $studentId 学生ID
     * @return JsonResponse
     */
    public function getSuggestions(string $studentId): JsonResponse
    {
        try {
            $suggestions = $this->mathRecSys->getLearningSuggestions($studentId);

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

        } catch (\Exception $e) {
            \Log::error('获取学习建议失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => '获取学习建议失败'
            ], 500);
        }
    }

    /**
     * 更新学生掌握度
     *
     * @param Request $request
     * @param string $studentId 学生ID
     * @return JsonResponse
     */
    public function updateMastery(Request $request, string $studentId): JsonResponse
    {
        $request->validate([
            'mastery_data' => 'required|array',
            'mastery_data.*.kp' => 'required|string',
            'mastery_data.*.level' => 'required|numeric|min:0|max:1',
        ]);

        try {
            // 使用本地的MasteryCalculator
            $masteryCalculator = app(\App\Services\MasteryCalculator::class);

            $kpCodes = array_map(function($item) {
                return $item['kp'];
            }, $request->mastery_data);

            // 批量更新掌握度
            $results = $masteryCalculator->batchUpdateMastery($studentId, $kpCodes);

            return response()->json([
                'success' => true,
                'data' => [
                    'student_id' => $studentId,
                    'updated_count' => count($results),
                    'results' => $results,
                ]
            ]);

        } catch (\Exception $e) {
            \Log::error('更新掌握度失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => '更新掌握度失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 检查MathRecSys服务状态
     *
     * @return JsonResponse
     */
    public function checkServiceHealth(): JsonResponse
    {
        $isHealthy = $this->mathRecSys->isHealthy();

        return response()->json([
            'success' => true,
            'healthy' => $isHealthy,
            'timestamp' => now()->toISOString()
        ]);
    }

    /**
     * 从本地数据库获取学生基本信息
     *
     * @param string $studentId
     * @return array
     */
    private function getLocalStudent(string $studentId): array
    {
        // 这里应该从Laravel数据库查询学生信息
        // 示例返回数据，实际应该查询数据库
        return [
            'id' => $studentId,
            'name' => '学生_' . substr($studentId, -3),
            'class' => '五年级一班',
            'grade' => '五年级',
            'created_at' => now()->subMonths(6)->toISOString(),
        ];
    }

    /**
     * 格式化掌握度数据
     *
     * @param array $profile
     * @return array
     */
    private function formatMasteryLevels(array $profile): array
    {
        $masteryData = $profile['data']['mastery'] ?? $profile['mastery'] ?? [];

        return array_map(function ($item) {
            return [
                'kp' => $item['kp'] ?? $item['kp_id'] ?? '',
                'level' => floatval($item['level'] ?? $item['mastery_level'] ?? 0),
                'practice_count' => $item['practice_count'] ?? 0,
                'success_rate' => floatval($item['success_rate'] ?? 0),
                'last_practice' => $item['last_practice'] ?? null
            ];
        }, $masteryData);
    }

    /**
     * 获取推荐（内部方法）
     *
     * @param string $studentId
     * @return array
     */
    private function getStudentRecommendations(string $studentId): array
    {
        try {
            $recommendations = $this->mathRecSys->getRecommendations($studentId, ['count' => 5]);
            return $recommendations['data'] ?? [];
        } catch (\Exception $e) {
            \Log::warning('获取推荐失败', ['error' => $e->getMessage()]);
            return [];
        }
    }
}
