<?php

declare(strict_types=1);

namespace System\Environment;

final class Environment
{
    /**
     * Loaded environment variables.
     *
     * @var array<string, string>
     */
    private static array $variables = [];

    /**
     * Load .env file.
     */
    public static function load(string $file): void
    {
        if (!is_file($file)) {
            throw new RuntimeException(".env file not found: {$file}");
        }

        $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        if ($lines === false) {
            throw new RuntimeException('Unable to read .env file.');
        }

        foreach ($lines as $line) {

            $line = trim($line);

            if ($line === '' || str_starts_with($line, '#')) {
                continue;
            }

            if (!str_contains($line, '=')) {
                continue;
            }

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

            $key = trim($key);
            $value = trim(trim($value), "\"'");

            self::$variables[$key] = $value;

            $_ENV[$key] = $value;

            putenv($key . '=' . $value);
        }
    }

    public static function get(string $key, mixed $default = null): mixed
    {
        return self::$variables[$key]
            ?? $_ENV[$key]
            ?? getenv($key)
            ?: $default;
    }
}