<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$checks = [];

// cURL
$curlVer = function_exists('curl_version') ? (curl_version()['version'] ?? 'unknown') : 'unknown';
$checks['curl'] = [
    'available' => function_exists('curl_init'),
    'version'   => $curlVer,
];

// PHP version
$checks['php'] = [
    'version' => PHP_VERSION,
    'ok'      => version_compare(PHP_VERSION, '7.4.0', '>='),
];

// pdftotext (for PDF extraction)
$pdfToText = '';
if (function_exists('shell_exec')) {
    $pdfToText = trim((string) (shell_exec('which pdftotext 2>/dev/null') ?? ''));
}
$checks['pdftotext'] = [
    'available' => $pdfToText !== '',
    'path'      => $pdfToText !== '' ? $pdfToText : 'not found',
];

// Upload dir writable
$checks['upload_dir'] = [
    'path'     => EXAM_UPLOAD_DIR,
    'writable' => is_dir(EXAM_UPLOAD_DIR) && is_writable(EXAM_UPLOAD_DIR),
];

// Export dir writable
$checks['export_dir'] = [
    'path'     => EXAM_EXPORT_DIR,
    'writable' => is_dir(EXAM_EXPORT_DIR) && is_writable(EXAM_EXPORT_DIR),
];

// Config keys set (placeholder check)
$checks['config'] = [
    'claude_key_set' => defined('CLAUDE_API_KEY') && CLAUDE_API_KEY !== 'YOUR_CLAUDE_API_KEY_HERE' && CLAUDE_API_KEY !== '',
    'groq_key_set'   => defined('GROQ_API_KEY')   && GROQ_API_KEY   !== 'YOUR_GROQ_API_KEY_HERE'   && GROQ_API_KEY   !== '',
    'gemini_key_set' => defined('GEMINI_API_KEY') && GEMINI_API_KEY !== 'YOUR_GEMINI_API_KEY_HERE' && GEMINI_API_KEY !== '',
];

echo json_encode($checks, JSON_PRETTY_PRINT);
