<?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';

$jobId = (int) ($_REQUEST['job_id'] ?? 0);
if ($jobId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Missing generation job id.']);
    exit;
}

$job = getExamGenerationJob($jobId, (int) $_SESSION['user_id']);
if (!$job) {
    echo json_encode(['success' => false, 'message' => 'Generation job not found.']);
    exit;
}

if (in_array($job['status'], ['queued', 'retrying'], true)) {
    spawnExamGenerationWorker($jobId);
    $job = getExamGenerationJob($jobId, (int) $_SESSION['user_id']) ?: $job;
}

if (($job['status'] ?? '') === 'completed' && !empty($job['exam_id'])) {
    echo json_encode(formatCompletedGenerationJobResponse($job, [
        'user_id' => (int) $_SESSION['user_id'],
        'role' => $_SESSION['role'] ?? ''
    ]));
    exit;
}

$response = [
    'success' => true,
    'queued' => true,
    'job_id' => (int) $job['id'],
    'status' => $job['status'],
    'message' => match ($job['status']) {
        'queued' => 'Generation request is queued.',
        'retrying' => 'Generation hit an error and will retry automatically.',
        'processing' => 'Generation is in progress.',
        'failed' => 'Generation failed after retries.',
        default => 'Generation job updated.'
    },
    'generator' => $job['generator_used'] ?? 'pending',
    'warnings' => $job['job_warnings'] ?? [],
    'details' => empty($job['last_error']) ? [] : [$job['last_error']],
    'attempts' => (int) ($job['attempts'] ?? 0),
    'max_attempts' => (int) ($job['max_attempts'] ?? 0),
    'logs' => getExamGenerationJobLogs((int) $job['id']),
];

if (($job['status'] ?? '') === 'failed') {
    $response['success'] = false;
}

echo json_encode($response);

