<?php

declare(strict_types=1);

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

myronSendBaselineSecurityHeaders();
MyronEnv::load(__DIR__ . '/.env');

$myronInstallerState = MyronInstallerState::fromProjectRoot(__DIR__);
$myronRequestUri = (string) ($_SERVER['REQUEST_URI'] ?? '/');
$myronRequestPath = myronRootDeploymentRequestPath($myronRequestUri);
$myronAdminBasePath = $myronInstallerState->adminBasePath();

if (myronRootDeploymentPathIsPrivateDottedPath($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)
    || myronRootDeploymentPathIsUnderBase($myronRequestPath, $myronAdminBasePath)
    || myronRootDeploymentPathIsAppRequest($myronRequestPath)
) {
    require __DIR__ . '/app/index.php';
    return;
}

if (myronRootDeploymentPathIsStaticAssetRequest($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->isInstalled()) {
    myronRedirect($myronInstallerState->installerUrl());
}

require __DIR__ . '/app/site/index.php';

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

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

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

function myronRootDeploymentPathIsAppRequest(string $path): bool
{
    return str_starts_with($path, '/api/v1/')
        || $path === '/verify-notification-email'
        || $path === '/.well-known'
        || str_starts_with($path, '/.well-known/')
        || str_starts_with($path, '/oauth/');
}

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

function myronRootDeploymentPathIsStaticAssetRequest(string $path): bool
{
    if (myronRootDeploymentPathIsDynamicVCardFileRequest($path)) {
        return false;
    }

    $basename = basename($path);
    return $basename !== '' && preg_match('/\\.[A-Za-z0-9]{1,16}$/', $basename) === 1;
}

function myronRootDeploymentPathIsDynamicVCardFileRequest(string $path): bool
{
    return preg_match('#^/vcards/[A-Za-z0-9_-]+\\.vcf$#', $path) === 1;
}
