<?php
header('Content-Type: application/json');
require_once dirname(__DIR__) . '/include/config.php';
require_once dirname(__DIR__) . '/include/common.php';

// Pull slow fields (docker/vm/top_procs/swap) from last full cache — stale is fine,
// these don't change on a per-second basis. 600s window so the card stays populated
// even if the full cache writer is temporarily behind.
$_full      = vv_cache_read('monitor', 600);
$_dockerKb  = $_full['mem']['docker_kb']      ?? 0;
$_vmKb      = $_full['mem']['vm_kb']          ?? 0;
$_topProcs  = $_full['mem']['top_procs']      ?? [];
$_swapTotal = $_full['mem']['swap_total_kb']  ?? 0;
$_swapUsed  = $_full['mem']['swap_used_kb']   ?? 0;

// Fast memory: /proc/meminfo + ZFS ARC (no docker stats, no GQL)
$_memRaw = [];
foreach (file('/proc/meminfo') ?: [] as $_l) {
    if (preg_match('/^(\w+):\s+(\d+)/', $_l, $_m)) $_memRaw[$_m[1]] = (int)$_m[2];
}
$_totalKb = $_memRaw['MemTotal']    ?? 0;
$_freeKb  = $_memRaw['MemAvailable'] ?? 0;
$_arcKb   = 0;
foreach (@file('/proc/spl/kstat/zfs/arcstats') ?: [] as $_l) {
    if (preg_match('/^size\s+\d+\s+(\d+)/', $_l, $_m)) { $_arcKb = (int)($_m[1] / 1024); break; }
}
if (!$_swapTotal) {
    $_swapTotal = $_memRaw['SwapTotal'] ?? 0;
    $_swapUsed  = max(0, ($_memRaw['SwapTotal'] ?? 0) - ($_memRaw['SwapFree'] ?? 0));
}

echo json_encode([
    'cpu' => vv_cpu_per_core(),
    'mem' => [
        'total_kb'      => $_totalKb,
        'free_kb'       => $_freeKb,
        'used_kb'       => max(0, $_totalKb - $_freeKb),
        'arc_kb'        => $_arcKb,
        'docker_kb'     => $_dockerKb,
        'vm_kb'         => $_vmKb,
        'system_kb'     => max(0, $_totalKb - $_freeKb - $_arcKb - $_dockerKb - $_vmKb),
        'swap_total_kb' => $_swapTotal,
        'swap_used_kb'  => $_swapUsed,
        'top_procs'     => $_topProcs,
    ],
    'net' => vv_network_stats(),
    'ts'  => time(),
]);
