<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/system/support/Support.php';
require_once dirname(__DIR__) . '/system/install/InstallerState.php';
require_once dirname(__DIR__) . '/system/performance/PublicPageCache.php';

$myronProjectRoot = dirname(__DIR__, 2);
if (!defined('MYRON_PUBLIC_SITE_REQUEST')) {
    define('MYRON_PUBLIC_SITE_REQUEST', true);
}
myronSendBaselineSecurityHeaders();
MyronEnv::load($myronProjectRoot . '/.env');
$myronInstallerState = MyronInstallerState::fromProjectRoot($myronProjectRoot);
if ((string) getenv('MYRON_APP_ENV') !== 'test' && !$myronInstallerState->isInstalled()) {
    myronRedirect($myronInstallerState->installerUrl());
}

$myronPublicPageCache = MyronPublicPageCache::fromProjectRoot($myronProjectRoot);
if ($myronPublicPageCache->tryServeFromRequest($_SERVER, $_COOKIE)) {
    return;
}

$myronRequestPath = parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH) ?: '/';
if ($myronRequestPath === '/api/analytics/collect') {
    require dirname(__DIR__) . '/api/routes/analytics-collect.php';
    return;
}

if (strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET')) === 'POST') {
    http_response_code(405);
    header('Allow: GET, HEAD');
    header('Content-Type: text/plain; charset=utf-8');
    header('X-Content-Type-Options: nosniff');
    echo 'Public form submissions must use a registered MyronCMS form endpoint.';
    return;
}

/** Stable public entrypoint shim. Canonical source: app/site/routes/index.php */
if ($myronPublicPageCache->shouldCaptureRequest($_SERVER, $_COOKIE)) {
    ob_start();
    try {
        require __DIR__ . '/routes/index.php';
        $myronPublicPageCachePayload = (string) ob_get_clean();
    } catch (Throwable $myronPublicPageCacheException) {
        if (ob_get_level() > 0) {
            ob_end_clean();
        }
        throw $myronPublicPageCacheException;
    }

    $myronPublicPageCache->storeResponseFromRequest(
        $_SERVER,
        $_COOKIE,
        $myronPublicPageCachePayload,
        http_response_code() ?: 200,
        headers_list()
    );
    echo $myronPublicPageCachePayload;
    return;
}

require __DIR__ . '/routes/index.php';
