<?php

use App\Services\LearningAnalyticsService;
use App\Services\QuestionBankService;
use App\Models\Student;
use Illuminate\Support\Facades\Log;

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

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

// Instantiate services
$qbService = app(QuestionBankService::class);
$laService = app(LearningAnalyticsService::class);

echo "=== Starting Exam Generation Flow Debug ===\n";

// 1. Test Student and Grade Standardization
$studentId = 'stu_1762395159_4'; // Use the ID from the error
echo "\n[1] Checking Student: $studentId\n";
$student = Student::find($studentId);

if (!$student) {
    echo "Error: Student not found! Using first available student.\n";
    $student = Student::first();
    if (!$student) {
        die("Error: No students found in database.\n");
    }
    $studentId = $student->student_id;
}

echo "Student Name: " . $student->name . "\n";
echo "Original Grade: " . $student->grade . "\n";

// Simulate Grade Standardization Logic
$grade = $student->grade;
$standardizedGrade = $grade;
if ($grade === '初一') $standardizedGrade = '七年级';
elseif ($grade === '初二') $standardizedGrade = '八年级';
elseif ($grade === '初三') $standardizedGrade = '九年级';

echo "Standardized Grade: $standardizedGrade\n";

// 2. Test Knowledge Graph API Fetching
echo "\n[2] Fetching Knowledge Points from KG API\n";
$filters = [];
if (str_contains($standardizedGrade, '初') || str_contains($standardizedGrade, '七年级') || str_contains($standardizedGrade, '八年级') || str_contains($standardizedGrade, '九年级')) {
    $filters['phase'] = '初中';
} elseif (str_contains($standardizedGrade, '高')) {
    $filters['phase'] = '高中';
}

echo "Filters: " . json_encode($filters, JSON_UNESCAPED_UNICODE) . "\n";

$kps = $laService->getKnowledgePoints($filters);
echo "KPs Fetched: " . count($kps) . "\n";

if (empty($kps)) {
    echo "Error: No KPs returned from KG API.\n";
    // Try without filters to see if API is working at all
    echo "Retrying without filters...\n";
    $allKps = $laService->getKnowledgePoints([]);
    echo "All KPs Fetched: " . count($allKps) . "\n";
    if (empty($allKps)) {
        die("Critical Error: KG API seems down or returning empty.\n");
    }
} else {
    echo "Sample KP: " . json_encode($kps[0], JSON_UNESCAPED_UNICODE) . "\n";
}

// 3. Select Random KPs
$kpCodes = [];
if (!empty($kps)) {
    $kpKeys = array_column($kps, 'kp_code');
    if (empty($kpKeys)) $kpKeys = array_column($kps, 'code');
    
    if (!empty($kpKeys)) {
        $randomKeys = array_rand(array_flip($kpKeys), min(5, count($kpKeys)));
        $kpCodes = is_array($randomKeys) ? $randomKeys : [$randomKeys];
    }
}

echo "\n[3] Selected KP Codes: " . implode(', ', $kpCodes) . "\n";

if (empty($kpCodes)) {
    die("Error: Could not select any KP codes.\n");
}

// 4. Test Question Bank API
echo "\n[4] Querying Question Bank API\n";

// Test 1: /questions/filter with kp_codes (Current implementation)
echo "Test 1: /questions/filter with kp_codes=R01\n";
$params1 = ['kp_codes' => 'R01', 'limit' => 10];
$res1 = $qbService->filterQuestions($params1);
echo "Result 1: " . (isset($res1['data']) ? count($res1['data']) : 'Error') . " questions.\n";

// Test 2: /questions with kp_code (Legacy implementation)
echo "Test 2: /questions with kp_code=R01\n";
$params2 = ['kp_code' => 'R01', 'limit' => 10];
$res2 = $qbService->listQuestions(1, 10, $params2);
echo "Result 2: " . (isset($res2['data']) ? count($res2['data']) : 'Error') . " questions.\n";

// Test 3: /questions with kp_codes (Maybe list supports plural?)
echo "Test 3: /questions with kp_codes=R01\n";
$params3 = ['kp_codes' => 'R01', 'limit' => 10];
$res3 = $qbService->listQuestions(1, 10, $params3);
echo "Result 3: " . (isset($res3['data']) ? count($res3['data']) : 'Error') . " questions.\n";

echo "\n[5] Inspecting Question Bank Data\n";
$allQuestions = $qbService->listQuestions(1, 10);
if (isset($allQuestions['data']) && count($allQuestions['data']) > 0) {
    echo "Total Questions in Bank (approx): " . ($allQuestions['meta']['total'] ?? 'Unknown') . "\n";
    echo "Sample Question from Bank:\n";
    $sampleQ = $allQuestions['data'][0];
    echo "ID: " . ($sampleQ['id'] ?? 'N/A') . "\n";
    echo "KP Code: " . ($sampleQ['kp_code'] ?? $sampleQ['knowledge_point'] ?? 'N/A') . "\n";
    echo "Content: " . substr($sampleQ['content'] ?? '', 0, 50) . "...\n";
} else {
    echo "Question Bank seems empty or listQuestions failed.\n";
    echo "Response: " . json_encode($allQuestions, JSON_UNESCAPED_UNICODE) . "\n";
}

echo "\n=== Debug Complete ===\n";
