<?php

declare(strict_types=1);

myronSendMcpOAuthNoStoreHeaders();
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');

if (strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'method_not_allowed'], JSON_UNESCAPED_SLASHES);
    return;
}

$headers = [];
if (function_exists('getallheaders')) {
    foreach ((array) getallheaders() as $name => $value) {
        $headers[(string) $name] = (string) $value;
    }
}
foreach ($_SERVER as $key => $value) {
    if (is_string($key) && str_starts_with($key, 'HTTP_')) {
        $headers[ucwords(str_replace('_', '-', strtolower(substr($key, 5))), '-')] = (string) $value;
    }
}

$input = $_POST;
if ($input === []) {
    $raw = (string) file_get_contents('php://input');
    $json = json_decode($raw, true);
    if (is_array($json)) {
        $input = $json;
    } else {
        parse_str($raw, $parsed);
        $input = is_array($parsed) ? $parsed : [];
    }
}

try {
    echo json_encode(myronMcpOAuthTokenService()->exchangeToken($input, $headers), JSON_UNESCAPED_SLASHES);
} catch (Throwable $exception) {
    $error = $exception->getMessage();
    $allowed = ['invalid_client', 'invalid_grant', 'invalid_target', 'unsupported_grant_type'];
    if (!in_array($error, $allowed, true)) {
        $error = 'invalid_request';
    }
    http_response_code($error === 'invalid_client' ? 401 : 400);
    echo json_encode(['error' => $error], JSON_UNESCAPED_SLASHES);
}

