<?php
/**
 * chat-queue.php — Job queue for APTUM agent
 *
 * POST  action=enqueue  {message, session_id, model} → {job_id}
 * GET   action=poll                                   → {job} | {job:null}
 * POST  action=claim    {job_id}                      → {ok}
 */

$JOBS_DIR = __DIR__ . '/jobs';
if (!is_dir($JOBS_DIR)) mkdir($JOBS_DIR, 0755, true);

header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
$body   = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $body['action'] ?? $_GET['action'] ?? '';

if ($method === 'POST' && $action === 'enqueue') {
    $job_id    = bin2hex(random_bytes(8));
    $session_id = $body['session_id'] ?? null;
    $job = [
        'job_id'     => $job_id,
        'session_id' => $session_id,
        'message'    => $body['message'] ?? '',
        'model'      => $body['model'] ?? 'llama-3.3-70b',
        'status'     => 'pending',
        'created_at' => time(),
    ];
    file_put_contents("$JOBS_DIR/$job_id.json", json_encode($job));
    // Create empty events file
    file_put_contents("$JOBS_DIR/$job_id.events.jsonl", '');
    echo json_encode(['job_id' => $job_id]);
    exit;
}

if ($method === 'GET' && $action === 'poll') {
    // Return oldest pending job
    $files = glob("$JOBS_DIR/*.json");
    usort($files, fn($a,$b) => filemtime($a) - filemtime($b));
    foreach ($files as $f) {
        $job = json_decode(file_get_contents($f), true);
        if (($job['status'] ?? '') === 'pending') {
            echo json_encode(['job' => $job]);
            exit;
        }
    }
    echo json_encode(['job' => null]);
    exit;
}

if ($method === 'POST' && $action === 'claim') {
    $job_id = $body['job_id'] ?? '';
    $f = "$JOBS_DIR/$job_id.json";
    if (!file_exists($f)) { echo json_encode(['ok' => false]); exit; }
    $job = json_decode(file_get_contents($f), true);
    $job['status'] = 'running';
    $job['claimed_at'] = time();
    file_put_contents($f, json_encode($job));
    echo json_encode(['ok' => true]);
    exit;
}

if ($method === 'POST' && $action === 'complete') {
    $job_id = $body['job_id'] ?? '';
    $session_id = $body['session_id'] ?? null;
    $f = "$JOBS_DIR/$job_id.json";
    if (file_exists($f)) {
        $job = json_decode(file_get_contents($f), true);
        $job['status'] = 'done';
        $job['completed_at'] = time();
        if ($session_id) $job['session_id'] = $session_id;
        file_put_contents($f, json_encode($job));
    }
    echo json_encode(['ok' => true]);
    exit;
}

echo json_encode(['error' => 'unknown action']);
