<?php
require_once __DIR__ . '/../config/database.php';

header('Content-Type: application/json');

if (!check_feature_flag('bot_games_enabled')) {
    http_response_code(403);
    echo json_encode(['error' => 'feature_disabled', 'message' => 'اللعب ضد البوت معطل حالياً']);
    exit;
}

$cacheFile = sys_get_temp_dir() . '/el3ab_bots_cache.json';
$cacheTTL = 300; // 5 minutes

if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTTL) {
    echo file_get_contents($cacheFile);
    exit;
}

$ch = curl_init(STOCKFISH_API . '/api/chess/bots');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'X-API-Key: ' . STOCKFISH_MGMT_KEY
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode === 200 && $response) {
    file_put_contents($cacheFile, $response);
    echo $response;
} else {
    if (file_exists($cacheFile)) {
        echo file_get_contents($cacheFile);
    } else {
        http_response_code(502);
        echo json_encode(['error' => 'bot_service_unavailable']);
    }
}
