<?php
declare(strict_types=1);

/**
 * Mini .env loader (ohne externe Dependencies).
 * Liest KEY=VALUE aus Projekt-Root .env.
 */

function env_load($path)
{
    if (!is_file($path)) return [];

    $vars = [];
    $lines = @file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (!is_array($lines)) return [];

    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || (isset($line[0]) && $line[0] === '#')) continue;

        $pos = strpos($line, '=');
        if ($pos === false) continue;

        $k = trim(substr($line, 0, $pos));
        $v = trim(substr($line, $pos + 1));

        // strip simple quotes
        $len = strlen($v);
        if ($len >= 2) {
            $first = $v[0];
            $last = $v[$len - 1];
            if (($first === '"' && $last === '"') || ($first === "'" && $last === "'")) {
                $v = substr($v, 1, -1);
            }
        }

        if ($k !== '') $vars[$k] = $v;
    }

    return $vars;
}

function env_get(array $vars, $key, $default = null)
{
    if (array_key_exists($key, $vars)) return (string)$vars[$key];
    $v = getenv((string)$key);
    if ($v !== false) return (string)$v;
    return $default;
}
