<?php

require __DIR__ . '/vendor/autoload.php';

$app = require_once __DIR__ . '/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

use App\Services\LearningAnalyticsService;

echo "=" . str_repeat("=", 60) . "\n";
echo "🚀 LearningAnalytics 学习数据生成器\n";
echo "=" . str_repeat("=", 60) . "\n\n";

// 初始化服务
$service = app(LearningAnalyticsService::class);

// 配置
$kpCodes = ['KP1001', 'KP1101', 'KP9003', 'KP8001', 'KP9002']; // 因式分解相关知识点
$studentsPerTeacher = 5;
$attemptsPerStudent = 30;

try {
    // 从LearningAnalytics获取知识点
    echo "📚 获取知识点列表...\n";
    $knowledgePoints = $service->getKnowledgePoints();
    echo "✅ 获取到 " . count($knowledgePoints) . " 个知识点\n\n";

    // 获取老师列表
    echo "👥 获取老师列表...\n";
    $teachers = DB::connection('remote_mysql')
        ->table('teachers')
        ->get()
        ->toArray();
    
    echo "✅ 找到 " . count($teachers) . " 个老师\n\n";

    $totalStudents = 0;
    $totalAttempts = 0;

    foreach ($teachers as $teacher) {
        echo "🎓 处理老师: {$teacher->teacher_id} - {$teacher->name}\n";
        echo str_repeat("-", 60) . "\n";

        // 获取该老师的学生
        $students = DB::connection('remote_mysql')
            ->table('students')
            ->where('teacher_id', $teacher->teacher_id)
            ->limit($studentsPerTeacher)
            ->get()
            ->toArray();

        echo "  📝 找到 " . count($students) . " 个学生\n";

        foreach ($students as $student) {
            echo "\n  👤 学生: {$student->student_id} - {$student->name}\n";
            echo "      班级: {$student->grade} {$student->class_name}\n";

            // 生成学习数据
            $attempts = [];
            $mastery = 0.3; // 初始掌握度
            
            // 生成30次答题记录
            for ($i = 0; $i < $attemptsPerStudent; $i++) {
                // 随机选择知识点
                $kpCode = $kpCodes[array_rand($kpCodes)];
                
                // 模拟学习进度：前10次错误较多，后面逐渐变好
                $isCorrect = false;
                if ($i < 10) {
                    $isCorrect = (rand(1, 100) <= 30); // 30% 正确率
                } elseif ($i < 20) {
                    $isCorrect = (rand(1, 100) <= 60); // 60% 正确率
                } else {
                    $isCorrect = (rand(1, 100) <= 80); // 80% 正确率
                }
                
                // 模拟答题时间（逐渐变快）
                $baseTime = 180;
                $timeSpent = max(60, $baseTime - ($i * 4) + rand(-20, 20));
                
                // 更新掌握度
                if ($isCorrect) {
                    $mastery = $mastery + (1 - $mastery) * 0.15;
                } else {
                    $mastery = $mastery - ($mastery * 0.08);
                }
                $mastery = max(0.1, min(0.95, $mastery)); // 限制在0.1-0.95之间
                
                $attempts[] = [
                    'kp_code' => $kpCode,
                    'is_correct' => $isCorrect,
                    'time_spent_seconds' => $timeSpent,
                    'difficulty_level' => rand(2, 4),
                    'mastery' => $mastery
                ];
            }

            // 提交到LearningAnalytics
            echo "      📤 提交学习数据到LearningAnalytics...\n";
            $successCount = 0;
            foreach ($attempts as $attempt) {
                $result = $service->updateMastery([
                    'student_id' => $student->student_id,
                    'kp_code' => $attempt['kp_code'],
                    'is_correct' => $attempt['is_correct'],
                    'time_spent_seconds' => $attempt['time_spent_seconds'],
                    'difficulty_level' => $attempt['difficulty_level']
                ]);

                if (isset($result['error']) && !$result['error']) {
                    $successCount++;
                }
            }

            $finalMastery = $mastery;
            echo "      ✅ 成功提交 {$successCount} 条记录\n";
            echo "      📊 最终掌握度: " . number_format($finalMastery * 100, 2) . "%\n";

            $totalStudents++;
            $totalAttempts += $successCount;
        }

        echo "\n";
    }

    echo "=" . str_repeat("=", 60) . "\n";
    echo "📈 生成完成！\n";
    echo "=" . str_repeat("=", 60) . "\n";
    echo "✅ 处理学生数: {$totalStudents}\n";
    echo "✅ 总答题记录: {$totalAttempts}\n";
    echo "✅ 平均每人: " . number_format($totalAttempts / max(1, $totalStudents), 1) . " 次\n";
    echo "\n🎉 所有学习数据已生成并同步到LearningAnalytics!\n";

} catch (Exception $e) {
    echo "❌ 错误: " . $e->getMessage() . "\n";
    echo "📍 位置: " . $e->getFile() . ":" . $e->getLine() . "\n";
    echo "\n" . str_repeat("=", 60) . "\n";
    exit(1);
}
