<?php
declare(strict_types=1);

/**
 * Tüm provider oyun listelerini API'den çekip önbelleğe yazar.
 * Canlı sunucuda: php api/slot_games_warm_cache.php
 */
require_once __DIR__ . '/slot_games_lib.php';

$isCli = PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg';
if (!$isCli) {
    header('Content-Type: application/json; charset=utf-8');
}

$providers = mocker_slot_list_providers();
$results = [];

foreach ($providers as $p) {
    $id = $p['id'];
    if ($isCli && $id !== ($providers[0]['id'] ?? '')) {
        usleep(400000);
    }
    $url = MOCKER_SLOT_API_ROULETTE . '?provider=' . rawurlencode($id);
    $raw = mocker_slot_http_get($url);
    $games = mocker_slot_resolve_games($id, $raw);
    $source = 'none';
    if ($raw !== null && $games !== []) {
        $source = 'api';
    } elseif (mocker_slot_read_games_cache($id) !== []) {
        $source = 'cache';
    }
    $results[] = [
        'provider' => $id,
        'ok' => count($games) > 0,
        'count' => count($games),
        'source' => $source,
    ];
    if ($isCli) {
        $status = count($games) > 0 ? 'OK' : 'FAIL';
        fwrite(STDOUT, sprintf("[%s] %s — %d oyun (%s)\n", $status, $id, count($games), $source));
    }
}

$okCount = count(array_filter($results, static fn ($r) => $r['ok']));

if ($isCli) {
    fwrite(STDOUT, sprintf("\nToplam: %d / %d provider\n", $okCount, count($providers)));
    exit($okCount === count($providers) ? 0 : 1);
}

echo json_encode(['ok' => $okCount > 0, 'results' => $results], JSON_UNESCAPED_UNICODE);
