<?php

function og_find_pingpong_env_path(): ?string
{
    static $resolved = null;
    if ($resolved !== null) {
        return $resolved;
    }

    $current = __DIR__;
    for ($i = 0; $i < 8; $i++) {
        $candidate = $current . '/disciplines/ping-pong/1v1/node-server/.env';
        if (is_file($candidate)) {
            $resolved = $candidate;
            return $resolved;
        }

        $parent = dirname($current);
        if ($parent === $current) {
            break;
        }
        $current = $parent;
    }

    $resolved = false;
    return null;
}

function og_parse_env_file(string $envPath): array
{
    $values = [];
    $lines = @file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (!is_array($lines)) {
        return $values;
    }

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

        $separatorPos = strpos($line, '=');
        if ($separatorPos === false) {
            continue;
        }

        $name = trim(substr($line, 0, $separatorPos));
        if ($name === '') {
            continue;
        }

        $value = trim(substr($line, $separatorPos + 1));
        $length = strlen($value);
        if ($length >= 2) {
            $firstChar = $value[0];
            $lastChar = $value[$length - 1];
            if (($firstChar === '"' && $lastChar === '"') || ($firstChar === "'" && $lastChar === "'")) {
                $value = substr($value, 1, -1);
            }
        }

        $values[$name] = $value;
    }

    return $values;
}

function og_env(string $name, ?string $default = null): ?string
{
    $value = getenv($name);
    if ($value !== false && $value !== '') {
        return $value;
    }

    static $envCache = null;
    if ($envCache === null) {
        $envPath = og_find_pingpong_env_path();
        if ($envPath && is_file($envPath)) {
            $envCache = og_parse_env_file($envPath);
        } else {
            $envCache = [];
        }
    }

    if (array_key_exists($name, $envCache) && $envCache[$name] !== '') {
        return (string) $envCache[$name];
    }

    return $default;
}