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

$logDir = LOG_DIR;
$runs   = [];

try {
    $ri = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($logDir, RecursiveDirectoryIterator::SKIP_DOTS)
    );
    foreach ($ri as $file) {
        if ($file->getExtension() !== 'json') continue;
        $d = @json_decode(@file_get_contents($file->getPathname()), true);
        if (!is_array($d) || empty($d['start']) || empty($d['status'])) continue;
        if ($d['status'] === 'running') continue;
        $id = (string)($d['id'] ?? '');
        $runs[] = [
            'id'     => $id,
            'label'  => basename(str_replace('.sh', '', $id)),
            'status' => $d['status'],
            'start'  => (int)$d['start'],
            'dur'    => isset($d['end']) ? max(0, (int)$d['end'] - (int)$d['start']) : 0,
        ];
    }
} catch (Exception $e) {}

usort($runs, fn($a, $b) => $b['start'] - $a['start']);
echo json_encode(['ok' => true, 'runs' => array_slice($runs, 0, 24)]);
