<?php
declare(strict_types=1);
// Stateless: accepts text only, never reads user-selected files or fetches URLs.
ini_set('display_errors', '0');
ini_set('memory_limit', '64M');
set_time_limit(3);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
header('X-Content-Type-Options: nosniff');
header("Content-Security-Policy: default-src 'none'; frame-ancestors 'none'");

function failRequest(int $status, string $message): never {
    http_response_code($status);
    echo json_encode(['ok' => false, 'error' => $message], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
    exit;
}
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    header('Allow: POST'); failRequest(405, 'Используйте POST с JSON.');
}
if (strtolower(trim(explode(';', $_SERVER['CONTENT_TYPE'] ?? '')[0])) !== 'application/json') {
    failRequest(415, 'Нужен Content-Type: application/json.');
}
if (isset($_SERVER['HTTP_SEC_FETCH_SITE']) && $_SERVER['HTTP_SEC_FETCH_SITE'] === 'cross-site') {
    failRequest(403, 'Запросы из другого сайта отключены.');
}
if ((int) ($_SERVER['CONTENT_LENGTH'] ?? 0) > 65536) { failRequest(413, 'JSON превышает 64 КиБ.'); }
$raw = file_get_contents('php://input', false, null, 0, 65537);
if ($raw === false || strlen($raw) > 65536) { failRequest(413, 'JSON превышает 64 КиБ.'); }
try {
    require dirname(__DIR__) . '/vendor/autoload.php';
    $data = json_decode($raw, true, 16, JSON_THROW_ON_ERROR);
    if (!is_array($data) || array_is_list($data)) { throw new InvalidArgumentException('Нужен JSON-объект.'); }
    $result = (new Aen\MarkdownLab\Converter())->request($data);
    echo json_encode($result, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (JsonException $e) { failRequest(400, 'Некорректный JSON или кодировка UTF-8.');
} catch (LengthException $e) { failRequest(413, $e->getMessage());
} catch (InvalidArgumentException $e) { failRequest(422, $e->getMessage());
} catch (Throwable $e) { failRequest(500, 'Конвертация недоступна. Проверьте Composer и mbstring на сервере.'); }
