<?php
/**
 * chat-push.php — VPS pushes streamed events here
 *
 * POST {job_id, events: [{event, data}]}
 */

$JOBS_DIR = __DIR__ . '/jobs';
header('Content-Type: application/json');

$body   = json_decode(file_get_contents('php://input'), true) ?? [];
$job_id = preg_replace('/[^a-f0-9]/', '', $body['job_id'] ?? '');
$events = $body['events'] ?? [];

if (!$job_id || !file_exists("$JOBS_DIR/$job_id.events.jsonl")) {
    http_response_code(404);
    echo json_encode(['error' => 'job not found']);
    exit;
}

$evfile = "$JOBS_DIR/$job_id.events.jsonl";
$fp = fopen($evfile, 'a');
if (!$fp) { echo json_encode(['error' => 'cannot write']); exit; }

foreach ($events as $ev) {
    fwrite($fp, json_encode($ev) . "\n");
}
fclose($fp);

echo json_encode(['ok' => true, 'count' => count($events)]);
