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

$configuredRegistrationToken = myronMcpOAuthRegistrationEnabled() ? myronMcpOAuthRegistrationToken() : '';
if ($configuredRegistrationToken === '') {
    http_response_code(403);
    echo json_encode(['error' => 'registration_disabled'], JSON_UNESCAPED_SLASHES);
    return;
}

$providedRegistrationToken = myronMcpOAuthRegisterBearerToken();
if ($providedRegistrationToken === '' || !hash_equals($configuredRegistrationToken, $providedRegistrationToken)) {
    http_response_code(401);
    header('WWW-Authenticate: Bearer error="invalid_token"');
    echo json_encode(['error' => 'invalid_token'], JSON_UNESCAPED_SLASHES);
    return;
}

$body = json_decode((string) file_get_contents('php://input'), true);
if (!is_array($body)) {
    http_response_code(400);
    echo json_encode(['error' => 'invalid_client_metadata'], JSON_UNESCAPED_SLASHES);
    return;
}

try {
    echo json_encode(myronMcpOAuthTokenService()->registerClient($body), JSON_UNESCAPED_SLASHES);
} catch (Throwable $exception) {
    http_response_code(400);
    echo json_encode([
        'error' => 'invalid_client_metadata',
        'error_description' => $exception->getMessage(),
    ], JSON_UNESCAPED_SLASHES);
}

function myronMcpOAuthRegistrationToken(): string
{
    foreach (['MYRON_MCP_OAUTH_REGISTRATION_TOKEN', 'MYRON_MCP_OAUTH_INITIAL_ACCESS_TOKEN'] as $key) {
        $value = trim((string) (getenv($key) ?: ''));
        if ($value !== '') {
            return $value;
        }
    }

    return '';
}

function myronMcpOAuthRegistrationEnabled(): bool
{
    return in_array(strtolower(trim((string) (getenv('MYRON_MCP_OAUTH_DCR_ENABLED') ?: ''))), ['1', 'true', 'yes', 'on'], true);
}

function myronMcpOAuthRegisterBearerToken(): string
{
    foreach (['HTTP_AUTHORIZATION', 'REDIRECT_HTTP_AUTHORIZATION', 'Authorization'] as $key) {
        $value = trim((string) ($_SERVER[$key] ?? ''));
        if ($value === '' || stripos($value, 'Bearer ') !== 0) {
            continue;
        }
        return trim(substr($value, 7));
    }

    return '';
}
