<?php
declare(strict_types=1);
require __DIR__ . '/lib.php';

$uriPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$mount = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/index.php')), '/');
$path = $mount !== '' && str_starts_with($uriPath, $mount . '/') ? substr($uriPath, strlen($mount)) : $uriPath;
$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$headers = requestHeaders();
$rule = matchRoute($path, $method, $headers, $ip);
$status = (int) ($rule['status'] ?? 200);

$input = fopen('php://input', 'rb');
$body = $input === false ? '' : (string) fread($input, 65537);
if ($input !== false) {
    fclose($input);
}
$truncated = strlen($body) > 65536;
$body = substr($body, 0, 65536);
$binary = preg_match('//u', $body) !== 1 || str_contains($body, "\0");
if ($binary) {
    $body = base64_encode($body);
}

try {
    appendLog([
        'time' => gmdate('c'),
        'ip' => $ip,
        'method' => $method,
        'path' => $path,
        'query' => $_SERVER['QUERY_STRING'] ?? '',
        'headers' => $headers,
        'body' => $body,
        'body_base64' => $binary,
        'body_truncated' => $truncated,
        'response_status' => $status,
        'route_id' => $rule['id'] ?? null,
    ]);
} catch (Throwable $e) {
    error_log('onebeat logging failed: ' . $e->getMessage());
    http_response_code(503);
    header('Content-Type: text/plain; charset=UTF-8');
    exit('Logging unavailable');
}

http_response_code($status);
header('Content-Type: ' . ($rule['content_type'] ?? 'text/plain; charset=UTF-8'));
header('Cache-Control: no-store');
header('X-Content-Type-Options: nosniff');
foreach ($rule['headers'] ?? [] as $header) {
    header($header['name'] . ': ' . $header['value'], false, $status);
}
echo $rule['body'] ?? "ok\n";
