<?php

declare(strict_types=1);

// Bound this application's web and CLI workers without changing other sites on the server.
ini_set('memory_limit', '256M');
register_shutdown_function(static function (): void {
    $peak = memory_get_peak_usage(true);
    if ($peak >= 192 * 1024 * 1024) {
        error_log('Darex memory warning: peak_bytes=' . $peak . ' limit=' . ini_get('memory_limit'));
    }
});

$envPath = __DIR__ . '/../.env.php';
$exampleEnvPath = __DIR__ . '/../.env.example.php';
$config = is_file($envPath) ? require $envPath : require $exampleEnvPath;

$settingsPath = (string) ($config['APP_SETTINGS_FILE'] ?? (__DIR__ . '/../storage/app_settings.php'));
if (is_file($settingsPath)) {
    $storedSettings = require $settingsPath;
    if (is_array($storedSettings)) {
        $storedValues = isset($storedSettings['values']) && is_array($storedSettings['values'])
            ? $storedSettings['values']
            : $storedSettings;
        $config = array_replace($config, $storedValues);
    }
}
$config['APP_SETTINGS_FILE'] = $settingsPath;

function config(string $key, $default = null)
{
    global $config;

    return $config[$key] ?? $default;
}

function appUrl(string $path): string
{
    return rtrim((string) config('APP_BASE_URL'), '/') . '/' . ltrim($path, '/');
}

function ensureRuntimeDirectories(): void
{
    foreach ([
        dirname((string) config('LOG_FILE')),
        dirname((string) config('PROMPT_CACHE_FILE')),
        dirname((string) config('STATE_FILE')),
        dirname((string) config('CHAT_HISTORY_FILE')),
        dirname((string) config('APP_SETTINGS_FILE')),
    ] as $path) {
        if ($path === '' || $path === '.') {
            continue;
        }
        if (!is_dir($path)) {
            mkdir($path, 0775, true);
        }
    }
}

ensureRuntimeDirectories();

$crestPath = __DIR__ . '/../lib/crest/crest.php';
if (is_file($crestPath)) {
    require_once $crestPath;
}
