"auth"])); } $action = $_REQUEST["action"] ?? "poll"; if ($action === "poll") { $next = null; $pending = 0; $files = glob("$DIR/task_*.json"); sort($files); foreach ($files as $f) { $d = @json_decode(@file_get_contents($f), true); if (!$d) continue; if (($d["status"] ?? "") === "pending") { if (!$next) { $next = $d; $next["_file"] = basename($f); $d["status"] = "dispatched"; $d["dispatched_at"] = date("c"); @file_put_contents($f, json_encode($d, JSON_PRETTY_PRINT)); } else { $pending++; } } } echo json_encode(["task"=>$next,"pending"=>$pending]); exit; } if ($action === "done") { $tf = basename($_REQUEST["file"] ?? ""); $result = $_REQUEST["result"] ?? $_POST["result"] ?? ""; $path = "$DIR/$tf"; if ($tf && file_exists($path)) { $d = json_decode(file_get_contents($path), true); $d["status"] = "done"; $d["completed_at"] = date("c"); $d["result"] = substr($result, 0, 2000); file_put_contents($path, json_encode($d, JSON_PRETTY_PRINT)); echo json_encode(["ok"=>true]); } else { echo json_encode(["error"=>"not found"]); } exit; } // Status $files = glob("$DIR/task_*.json"); $stats = ["pending"=>0,"dispatched"=>0,"done"=>0,"total"=>count($files)]; foreach ($files as $f) { $d = @json_decode(@file_get_contents($f), true); $s = $d["status"] ?? "?"; if (isset($stats[$s])) $stats[$s]++; } $hb = @json_decode(@file_get_contents("$DIR/heartbeat.json"), true); echo json_encode(["stats"=>$stats,"heartbeat"=>$hb]);