<?php
/**
 * Ragreen - Minimal .env loader
 * No Composer dependency (vlucas/phpdotenv etc.) — this project stays
 * plain PHP, so a ~15-line parser is enough. Supports KEY=VALUE lines,
 * blank lines, and #-comments. Values can optionally be wrapped in
 * quotes; everything else is taken literally (no interpolation).
 */

function load_env(string $path): void
{
    if (!is_file($path)) {
        return;
    }

    foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) {
            continue;
        }

        [$key, $value] = explode('=', $line, 2);
        $key = trim($key);
        $value = trim($value);

        // Strip one layer of surrounding quotes, if present.
        if (strlen($value) >= 2 && (
            ($value[0] === '"' && $value[-1] === '"') ||
            ($value[0] === "'" && $value[-1] === "'")
        )) {
            $value = substr($value, 1, -1);
        }

        if (!array_key_exists($key, $_ENV)) {
            $_ENV[$key] = $value;
            putenv("$key=$value");
        }
    }
}

function env(string $key, $default = null)
{
    return $_ENV[$key] ?? getenv($key) ?: $default;
}
