<?php
declare(strict_types=1);

/**
 * paths.php
 *
 * Single source of resolved paths + merged config (system/.env + app .env).
 * No other file should ever hardcode a filesystem or URL path — everything
 * goes through paths_get() / paths_env().
 */

$__paths = null;

/**
 * Parse a simple KEY=VALUE .env file. No external dependency.
 */
function paths_load_env(string $file): array
{
    if (!is_file($file)) {
        return [];
    }

    $env = [];
    $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#') {
            continue;
        }
        $parts = explode('=', $line, 2);
        if (count($parts) !== 2) {
            continue;
        }
        [$key, $value] = $parts;
        $env[trim($key)] = trim($value, " \t\"'");
    }
    return $env;
}

/**
 * Resolve and cache all paths + merged env for the current request.
 * Must be called once, early, by bootstrap.php — $app_dir is the calling
 * app's own directory (pass __DIR__ from the app's index file).
 */
function paths_init(string $app_dir): void
{
    global $__paths;
    if ($__paths !== null) {
        return; // already resolved for this request
    }

    // system/ is one level below the project root.
    $root_dir   = dirname(__DIR__);
    $system_env = paths_load_env($root_dir . '/system/.env');
    $app_env    = paths_load_env($app_dir . '/.env');

    // App-level .env values override system-level ones.
    $env = array_merge($system_env, $app_env);

    $__paths = [
        'root_dir'    => $root_dir,
        'system_dir'  => $root_dir . '/system',
        'app_dir'     => $app_dir,
        'base_url'    => rtrim($env['BASE_URL'] ?? '', '/'),
        'uploads_dir' => $root_dir . '/' . trim($env['UPLOADS_DIR'] ?? 'uploads', '/'),
        'env'         => $env,
    ];
}

/**
 * Fetch a resolved path/value by key (root_dir, system_dir, app_dir,
 * base_url, uploads_dir, ...). Falls back to raw env if not a known path key.
 */
function paths_get(string $key): string
{
    global $__paths;
    if ($__paths === null) {
        throw new RuntimeException('paths_init() must be called before paths_get().');
    }
    if (array_key_exists($key, $__paths) && is_string($__paths[$key])) {
        return $__paths[$key];
    }
    return $__paths['env'][$key] ?? '';
}

/**
 * Fetch a raw config value from the merged system+app .env, with a default.
 */
function paths_env(string $key, string $default = ''): string
{
    global $__paths;
    if ($__paths === null) {
        throw new RuntimeException('paths_init() must be called before paths_env().');
    }
    return $__paths['env'][$key] ?? $default;
}
