<?php
require __DIR__ . '/auth.php';
mvlog_require_login();
$config = require __DIR__ . '/config.php';
header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
$jobs = [];
$dirs = glob($config['uploads_dir'] . '/*', GLOB_ONLYDIR) ?: [];
foreach ($dirs as $dir) {
    $name = basename($dir);
    $stateFile = $dir . '/.movmaker-state.json';
    $lockDir = $dir . '/.movmaker-lock';
    $state = is_file($stateFile) ? json_decode((string)file_get_contents($stateFile), true) : [];
    $status = is_array($state) ? (string)($state['status'] ?? '') : '';
    $locked = is_dir($lockDir);
    if ($locked || $status === 'processing') {
        $started = '';
        if (is_file($lockDir . '/started_at')) $started = trim((string)file_get_contents($lockDir . '/started_at'));
        if ($started === '' && is_array($state)) $started = (string)($state['started_at'] ?? $state['updated_at'] ?? '');
        $jobs[] = [
            'name' => $name,
            'status' => $status ?: ($locked ? 'processing' : 'unknown'),
            'started_at' => $started,
        ];
    }
}
echo json_encode(['jobs' => $jobs, 'checked_at' => date('c')], JSON_UNESCAPED_UNICODE);
