<?php

declare(strict_types=1);

if (!function_exists('iav_load_env')) {
    /**
     * Load a simple KEY=VALUE environment file without overwriting server values.
     */
    function iav_load_env(string $path): void
    {
        if (!is_readable($path)) {
            return;
        }

        $values = parse_ini_file($path, false, INI_SCANNER_RAW);
        if ($values === false) {
            throw new RuntimeException('Unable to parse the environment file.');
        }

        foreach ($values as $key => $value) {
            if (getenv((string) $key) !== false) {
                continue;
            }

            $clean = trim((string) $value);
            putenv($key . '=' . $clean);
            $_ENV[$key] = $clean;
            $_SERVER[$key] = $clean;
        }
    }
}

if (!function_exists('iav_env')) {
    /**
     * Read and normalize one environment value.
     */
    function iav_env(string $key, mixed $default = null): mixed
    {
        $value = getenv($key);
        if ($value === false) {
            return $default;
        }

        $normalized = strtolower(trim((string) $value));

        return match ($normalized) {
            'true', '(true)' => true,
            'false', '(false)' => false,
            'null', '(null)' => null,
            'empty', '(empty)' => '',
            default => $value,
        };
    }
}
