<?php

namespace Core\System;

class Env
{
    private static bool $bootstrapped = false;

    public static function bootstrap(?string $rootPath = null): void
    {
        if (self::$bootstrapped) {
            return;
        }

        self::$bootstrapped = true;

        $root = rtrim((string)($rootPath ?: (defined('ROOT_PATH') ? ROOT_PATH : dirname(__DIR__, 2))), '/');
        $envPath = $root . '/.env';

        if (!is_readable($envPath)) {
            return;
        }

        $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
        foreach ($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);
            $value = trim($value, " \t\n\r\0\x0B\"'");

            if ($key === '') {
                continue;
            }

            if (getenv($key) === false) {
                putenv($key . '=' . $value);
                $_ENV[$key] = $value;
                $_SERVER[$key] = $_SERVER[$key] ?? $value;
            }
        }
    }

    public static function get(string $key, ?string $default = null): ?string
    {
        self::bootstrap();

        $value = getenv($key);
        if ($value === false || $value === '') {
            return $default;
        }

        return (string)$value;
    }

    public static function bool(string $key, bool $default = false): bool
    {
        $value = self::get($key);
        if ($value === null) {
            return $default;
        }

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

    public static function appEnv(): string
    {
        return strtolower(self::get('APP_ENV', 'production') ?? 'production');
    }

    public static function isDebug(): bool
    {
        if (self::bool('APP_DEBUG', false)) {
            return true;
        }

        return self::appEnv() !== 'production';
    }
}
