<?php
/**
 * chat-events.php — Browser polls for new events
 *
 * GET ?job_id=X&since=N  → {events: [...], done: bool}
 */

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

$job_id = preg_replace('/[^a-f0-9]/', '', $_GET['job_id'] ?? '');
$since  = max(0, (int)($_GET['since'] ?? 0));

if (!$job_id) { echo json_encode(['error' => 'no job_id']); exit; }

$evfile  = "$JOBS_DIR/$job_id.events.jsonl";
$jobfile = "$JOBS_DIR/$job_id.json";

if (!file_exists($evfile)) {
    echo json_encode(['error' => 'job not found', 'events' => [], 'done' => false]);
    exit;
}

// Read all events, return only those after offset $since
clearstatcache();
$lines  = file($evfile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$new    = array_slice($lines, $since);
$events = array_map(fn($l) => json_decode($l, true), $new);

$done = false;
if (file_exists($jobfile)) {
    $job  = json_decode(file_get_contents($jobfile), true);
    $done = ($job['status'] ?? '') === 'done';
    // Auto-cleanup after 10 minutes
    if ($done && time() - ($job['completed_at'] ?? 0) > 600) {
        @unlink($evfile);
        @unlink($jobfile);
    }
}

echo json_encode([
    'events' => $events,
    'next'   => $since + count($new),
    'done'   => $done,
]);
