<?php

declare(strict_types=1);

require_once __DIR__ . '/system/support/Support.php';
require_once __DIR__ . '/system/install/InstallerState.php';

$myronProjectRoot = dirname(__DIR__);
myronSendBaselineSecurityHeaders();
MyronEnv::load($myronProjectRoot . '/.env');
$myronInstallerState = MyronInstallerState::fromProjectRoot($myronProjectRoot);
$myronRequestUri = (string) ($_SERVER['REQUEST_URI'] ?? '/');
$myronRequestPath = myronAppEntrypointRequestPath($myronRequestUri);
if (myronAppEntrypointPathIsPrivateDottedPath($myronRequestPath)) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    header('X-Content-Type-Options: nosniff');
    echo 'Not found.';
    return;
}
if ($myronInstallerState->isInstallerRequest($myronRequestUri)) {
    require __DIR__ . '/install/index.php';
    return;
}
if (!$myronInstallerState->isInstalled()) {
    myronRedirect($myronInstallerState->installerUrl());
}
if (str_starts_with($myronRequestPath, '/api/v1/') || $myronRequestPath === '/verify-notification-email') {
    require_once __DIR__ . '/system/bootstrap.php';
    require_once __DIR__ . '/system/routing/AppFrontController.php';
    myronDispatchAppRequest();
    return;
}
if (
    $myronRequestPath === '/.well-known'
    || str_starts_with($myronRequestPath, '/.well-known/')
    || str_starts_with($myronRequestPath, '/oauth/')
) {
    require_once __DIR__ . '/system/bootstrap.php';
    require_once __DIR__ . '/system/routing/AppFrontController.php';
    myronDispatchAppRequest();
    return;
}
if (
    !myronAppEntrypointPathIsUnderBase($myronRequestPath, $myronInstallerState->adminBasePath())
    && myronAppEntrypointPathIsPublicRequest($myronRequestPath)
) {
    require __DIR__ . '/site/index.php';
    return;
}

require_once __DIR__ . '/system/bootstrap.php';
require_once __DIR__ . '/system/routing/AppFrontController.php';

myronDispatchAppRequest();

function myronAppEntrypointRequestPath(string $requestUri): string
{
    $path = parse_url($requestUri, PHP_URL_PATH);
    $normalized = is_string($path) ? $path : '/';
    $normalized = '/' . ltrim($normalized, '/');
    return preg_replace('#/+#', '/', $normalized) ?: '/';
}

function myronAppEntrypointPathIsUnderBase(string $path, string $basePath): bool
{
    if ($basePath === '') {
        return false;
    }

    return $path === $basePath || str_starts_with($path, $basePath . '/');
}

function myronAppEntrypointPathIsPublicRequest(string $path): bool
{
    $publicBasePath = myronPublicBasePath();
    if ($publicBasePath === '') {
        return true;
    }

    return $path === $publicBasePath || str_starts_with($path, $publicBasePath . '/');
}

function myronAppEntrypointPathIsPrivateDottedPath(string $path): bool
{
    return preg_match('#^/\\.(?!well-known(?:/|$))#', $path) === 1;
}
