<?php
declare(strict_types=1);

// Ensure clean UTF-8 JSON output
@ini_set('default_charset', 'UTF-8');

// JSON endpoint for server status (used for async UI updates)

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

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

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

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

$serverStatus = null;
$cacheTs = 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'])) {
            $cacheTs = (int)$decoded['ts'];
            $age = time() - $cacheTs;
            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));
}

// index by url + normalized url (trailing slash removed)
$byUrl = [];
$byUrlNormalized = [];
foreach ($serverStatus as $svc) {
    if (!empty($svc['url']) && is_string($svc['url'])) {
        $u = $svc['url'];
        $byUrl[$u] = $svc;
        $byUrlNormalized[rtrim($u, '/')] = $svc;
    }
}

$json = json_encode([
    'ts' => time(),
    'data' => $serverStatus,
    'byUrl' => $byUrl,
    'byUrlNormalized' => $byUrlNormalized,
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

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

// Write as raw bytes to avoid any output-encoding conversion.
fwrite(STDOUT, $json);

