<?php
/**
 * NIS2 Agile - Environment Loader
 *
 * Carica variabili d'ambiente dal file .env
 */

class Env
{
    private static bool $loaded = false;
    private static array $vars = [];

    /**
     * Carica il file .env
     */
    public static function load(?string $path = null): void
    {
        if (self::$loaded) {
            return;
        }

        $path = $path ?? dirname(__DIR__, 2) . '/.env';

        if (!file_exists($path)) {
            self::$loaded = true;
            return;
        }

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

        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line) || str_starts_with($line, '#')) {
                continue;
            }

            if (strpos($line, '=') !== false) {
                [$key, $value] = explode('=', $line, 2);
                $key = trim($key);
                $value = trim($value);
                $value = trim($value, '"\'');

                self::$vars[$key] = $value;
                putenv("{$key}={$value}");
                $_ENV[$key] = $value;
            }
        }

        self::$loaded = true;
    }

    /**
     * Ottiene una variabile d'ambiente
     */
    public static function get(string $key, mixed $default = null): mixed
    {
        self::load();

        if (isset(self::$vars[$key]) && self::$vars[$key] !== '') {
            return self::$vars[$key];
        }

        $value = getenv($key);
        if ($value !== false && $value !== '') {
            return $value;
        }

        if (isset($_ENV[$key]) && $_ENV[$key] !== '') {
            return $_ENV[$key];
        }

        return $default;
    }

    /**
     * Verifica se una variabile esiste e non e' vuota
     */
    public static function has(string $key): bool
    {
        $value = self::get($key);
        return $value !== null && $value !== '';
    }

    /**
     * Ottiene una variabile OBBLIGATORIA
     */
    public static function getRequired(string $key): string
    {
        $value = self::get($key);

        if ($value === null || $value === '') {
            throw new RuntimeException(
                "Variabile d'ambiente obbligatoria '{$key}' non configurata. " .
                "Aggiungerla al file .env"
            );
        }

        return $value;
    }

    /**
     * Ottiene come booleano
     */
    public static function bool(string $key, bool $default = false): bool
    {
        $value = self::get($key);

        if ($value === null) {
            return $default;
        }

        return in_array(strtolower($value), ['true', '1', 'yes', 'on'], true);
    }

    /**
     * Ottiene come intero
     */
    public static function int(string $key, int $default = 0): int
    {
        $value = self::get($key);
        return $value !== null ? (int)$value : $default;
    }
}

// Auto-carica all'inclusione
Env::load();
