<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

require_once '../config.php';
require_once '../lib/exam_generation_service.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || ($_POST['action'] ?? '') !== 'generate') {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$requestData = normalizeGenerationRequest($_POST);
$validation = validateGenerationRequest($requestData);
if (!$validation['valid']) {
    echo json_encode([
        'success' => false,
        'message' => 'The generation request is incomplete.',
        'details' => $validation['errors'],
    ]);
    exit;
}

$jobId = createExamGenerationJob($requestData, (int) $_SESSION['user_id']);
$spawned = spawnExamGenerationWorker($jobId);
$message = $spawned
    ? 'Generation queued. The worker is preparing your draft in the background.'
    : 'Generation queued. Polling will continue while the worker is prepared.';

echo json_encode([
    'success' => true,
    'queued' => true,
    'job_id' => $jobId,
    'status' => 'queued',
    'message' => $message,
    'generator' => 'queued',
    'details' => [],
    'logs' => getExamGenerationJobLogs($jobId),
]);

