<?php

declare(strict_types=1);

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

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')),
    ] as $path) {
        if (!is_dir($path)) {
            mkdir($path, 0775, true);
        }
    }
}

ensureRuntimeDirectories();

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