<?php
declare(strict_types=1);

define('BASE_PATH', dirname(__DIR__));

spl_autoload_register(function (string $class): void {
    $prefixes = ['App\\' => BASE_PATH . '/app/', 'Modules\\' => BASE_PATH . '/modules/'];
    foreach ($prefixes as $prefix => $directory) {
        if (!str_starts_with($class, $prefix)) continue;
        $file = $directory . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';
        if (is_file($file)) require_once $file;
        return;
    }
});

App\Core\Env::load(BASE_PATH . '/.env');
$app = App\Foundation\Foundation::boot(BASE_PATH);
$production = strtolower((string)($_ENV['APP_ENV'] ?? 'production')) === 'production';
ini_set('display_errors', $production ? '0' : (filter_var($_ENV['APP_DEBUG'] ?? false, FILTER_VALIDATE_BOOL) ? '1' : '0'));
ini_set('display_startup_errors', '0');
ini_set('log_errors', '1');
error_reporting(E_ALL);

session_name($_ENV['SESSION_NAME'] ?? 'CDASESSID');
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.use_trans_sid', '0');
ini_set('session.cookie_httponly', '1');
$trustedProxy = filter_var($_ENV['TRUST_PROXY_HEADERS'] ?? false, FILTER_VALIDATE_BOOL);
$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    || ($trustedProxy && strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https');
$forceHttps = filter_var($_ENV['FORCE_HTTPS'] ?? false, FILTER_VALIDATE_BOOL);
if ($forceHttps && !$isHttps) {
    $host = preg_replace('/[^A-Za-z0-9.:-]/', '', (string)($_SERVER['HTTP_HOST'] ?? ''));
    $uri = (string)($_SERVER['REQUEST_URI'] ?? '/');
    if ($host !== '') { header('Location: https://' . $host . $uri, true, 308); exit; }
}
$sameSite = (string)($_ENV['SESSION_SAMESITE'] ?? 'Lax');
if (!in_array($sameSite, ['Lax', 'Strict'], true)) $sameSite = 'Lax';
$cookieSecure = $isHttps || filter_var($_ENV['SESSION_COOKIE_SECURE'] ?? false, FILTER_VALIDATE_BOOL);
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'secure' => $cookieSecure,
    'httponly' => true,
    'samesite' => $sameSite,
]);
session_start();
App\Security\HttpSecurityHeaders::apply($isHttps);
set_exception_handler(static function (\Throwable $error): void {
    $incident = bin2hex(random_bytes(8));
    error_log(sprintf(
        '[AXIOM:%s] %s in %s:%d',
        $incident,
        $error->getMessage(),
        $error->getFile(),
        $error->getLine()
    ));
    if (!headers_sent()) {
        http_response_code(500);
        header('Content-Type: text/plain; charset=utf-8');
    }
    echo '<pre>';
echo "INCIDENT : {$incident}\n\n";
echo get_class($error) . "\n\n";
echo $error->getMessage() . "\n\n";
echo $error->getFile() . ':' . $error->getLine() . "\n\n";
echo $error->getTraceAsString();
echo '</pre>';
});

(new App\Services\SystemIntegrityService())->enforce();

$router = new App\Core\Router($app->container());
$routeManager = new App\Core\Routing\RouteManager(
    $router,
    BASE_PATH . '/routes',
    BASE_PATH . '/storage/cache/routes.php'
);
$routeManager->load();
$app->container()->get(App\Runtime\ModuleRuntime::class)->registerRoutes($router);
$app->container()->set(App\Core\Router::class, $router);
$app->container()->set(App\Core\Routing\RouteManager::class, $routeManager);



$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';

/*
|--------------------------------------------------------------------------
| Suppression du préfixe /public
|--------------------------------------------------------------------------
*/
if (str_starts_with($path, '/public')) {
    $path = substr($path, strlen('/public'));

    if ($path === '') {
        $path = '/';
    }
}

$router->dispatch(
    $_SERVER['REQUEST_METHOD'] ?? 'GET',
    $path
);
