<?php
declare(strict_types=1);

// JSON endpoint for async status badge updates.
// Important: output must be clean UTF-8 JSON.

require_once __DIR__ . '/../includes/lib/server_status.php';
$serverStatusTargets = require __DIR__ . '/../includes/config/server_status_targets.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, max-age=0');

$cacheTtlSeconds = 30;
$cacheKey = 'server_status_api_v1';
$cacheFile = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $cacheKey . '.json';

$noCache = isset($_GET['nocache']) && $_GET['nocache'] === '1';

$serverStatus = null;
if (!$noCache && is_file($cacheFile)) {
    $raw = @file_get_contents($cacheFile);
    if ($raw !== false) {
        $decoded = json_decode($raw, true);
        if (is_array($decoded) && isset($decoded['ts'], $decoded['data']) && is_array($decoded['data'])) {
            $age = time() - (int)$decoded['ts'];
            if ($age >= 0 && $age <= $cacheTtlSeconds) {
                $serverStatus = $decoded['data'];
            }
        }
    }
}

if (!is_array($serverStatus)) {
    $serverStatus = build_server_status($serverStatusTargets);
    @file_put_contents($cacheFile, json_encode(['ts' => time(), 'data' => $serverStatus], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
}

$byUrlNormalized = [];
foreach ($serverStatus as $svc) {
    if (!empty($svc['url']) && is_string($svc['url'])) {
        $byUrlNormalized[rtrim($svc['url'], '/')] = $svc;
    }
}

$payload = json_encode([
    'ts' => time(),
    'byUrlNormalized' => $byUrlNormalized,
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

if ($payload === false) {
    http_response_code(500);
    $payload = '{"error":"json_encode_failed"}';
}

echo $payload;

