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

// ── Manual remote refresh — runs remote_arr_cache_writer for one host ─────────
$_action = trim($_GET['action'] ?? '');
if ($_action === 'refresh_remote') {
    $host = strtolower(trim($_GET['host'] ?? ''));
    if (!preg_match('/^host\d+$/', $host)) {
        echo json_encode(['ok' => false, 'error' => 'Invalid host']); exit;
    }
    $script = dirname(__DIR__) . '/Tools/remote_arr_cache_writer.sh';
    if (!file_exists($script)) {
        echo json_encode(['ok' => false, 'error' => 'remote_arr_cache_writer.sh not found']); exit;
    }
    set_time_limit(30);
    $out = []; $exit = 0;
    exec('bash ' . escapeshellarg($script) . ' --host=' . escapeshellarg(strtoupper($host)) . ' 2>&1', $out, $exit);

    $cacheFile = VV_CACHE_DIR . '/arrs_remote_' . $host . '.json';
    $node = null;
    if (file_exists($cacheFile)) {
        $node = json_decode(file_get_contents($cacheFile), true) ?: null;
        if ($node) {
            $node['cached']    = true;
            $node['cache_age'] = time() - (int)filemtime($cacheFile);
        }
    }
    // Bust the main arrs cache so next poll gets fresh data
    @unlink(VV_CACHE_DIR . '/arrs.json');
    echo json_encode(['ok' => $exit === 0, 'node' => $node, 'output' => implode("\n", $out)]);
    exit;
}
unset($_action);

// ── Normal data load ──────────────────────────────────────────────────────────
$_vv_cached = vv_cache_read('arrs', 300);
if ($_vv_cached !== null) { echo json_encode($_vv_cached); exit; }
unset($_vv_cached);

require_once dirname(__DIR__) . '/include/arrs.php';
echo json_encode(vv_arrs_all());
