<?php

use App\Services\LearningAnalyticsService;
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();

$service = app(LearningAnalyticsService::class);

echo "Fetching Knowledge Points from Learning Analytics Service...\n";
$kps = $service->getKnowledgePoints();
echo "Total KPs fetched from LA: " . count($kps) . "\n";

if (empty($kps)) {
    echo "LA Service returned empty. Trying Knowledge Graph API directly...\n";
    $kgBaseUrl = config('services.knowledge_api.base_url', 'http://localhost:5011');
    echo "KG Base URL: $kgBaseUrl\n";
    
    try {
        echo "Testing KG API with phase=初中...\n";
        $response = \Illuminate\Support\Facades\Http::timeout(5)->get($kgBaseUrl . '/knowledge-points/', ['phase' => '初中']);
        if ($response->successful()) {
            $kps = $response->json()['data'] ?? [];
            echo "KPs with phase=初中: " . count($kps) . "\n";
        }

        echo "Testing KG API with grade=七年级...\n";
        $response = \Illuminate\Support\Facades\Http::timeout(5)->get($kgBaseUrl . '/knowledge-points/', ['grade' => '七年级']);
        if ($response->successful()) {
            $kps = $response->json()['data'] ?? [];
            echo "KPs with grade=七年级: " . count($kps) . "\n";
        }
        
        // Fallback to fetch all if filtering fails for now to continue script
        $response = \Illuminate\Support\Facades\Http::timeout(5)->get($kgBaseUrl . '/knowledge-points/');
        $kps = $response->json()['data'] ?? [];
        
    } catch (\Exception $e) {
        echo "KG API Exception: " . $e->getMessage() . "\n";
    }
}

if (!empty($kps)) {
    echo "First KP structure:\n";
    print_r($kps[0]);
}

$studentId = 'stu_1762395159_4'; 
echo "\nSimulating filtering for student ID: $studentId\n";

$student = \App\Models\Student::find($studentId);
if ($student) {
    echo "Student found: " . $student->name . ", Grade: " . $student->grade . "\n";
    $grade = $student->grade;
    
    $filteredKps = array_filter($kps, function($kp) use ($grade) {
        $book = $kp['book'] ?? '';
        // Add Junior High logic
        if (str_contains($grade, '初一') || str_contains($grade, '七年级')) {
             return str_contains($book, '七年级');
        } elseif (str_contains($grade, '初二') || str_contains($grade, '八年级')) {
             return str_contains($book, '八年级');
        } elseif (str_contains($grade, '初三') || str_contains($grade, '九年级')) {
             return str_contains($book, '九年级');
        }
        
        if (str_contains($grade, '高一')) {
            return str_contains($book, '必修') || str_contains($book, '第一册') || str_contains($book, '第二册');
        } elseif (str_contains($grade, '高二')) {
            return str_contains($book, '选择性必修') || str_contains($book, '第三册');
        }
        return true;
    });
    
    echo "Filtered KPs count: " . count($filteredKps) . "\n";
    if (!empty($filteredKps)) {
        echo "Sample filtered KP book: " . $filteredKps[array_key_first($filteredKps)]['book'] . "\n";
    }
} else {
    echo "Student not found in local DB.\n";
    // Try to find ANY student to test
    $anyStudent = \App\Models\Student::first();
    if ($anyStudent) {
        echo "Testing with existing student: " . $anyStudent->name . " (" . $anyStudent->grade . ")\n";
         $grade = $anyStudent->grade;
         $filteredKps = array_filter($kps, function($kp) use ($grade) {
            $book = $kp['book'] ?? '';
            if (str_contains($grade, '高一')) {
                return str_contains($book, '必修') || str_contains($book, '第一册') || str_contains($book, '第二册');
            } elseif (str_contains($grade, '高二')) {
                return str_contains($book, '选择性必修') || str_contains($book, '第三册');
            }
            return true;
        });
        echo "Filtered KPs count: " . count($filteredKps) . "\n";
    }
}
