<?php
namespace boru\ai\Config;

class Dotenv
{
    public static function load(array $paths, $overrideExisting = false)
    {
        foreach ($paths as $path) {
            if (!is_string($path) || trim($path) === '' || !file_exists($path) || !is_readable($path)) {
                continue;
            }

            $lines = file($path, FILE_IGNORE_NEW_LINES);
            if (!is_array($lines)) {
                continue;
            }

            foreach ($lines as $line) {
                static::parseLine($line, $overrideExisting);
            }
        }
    }

    protected static function parseLine($line, $overrideExisting)
    {
        $line = trim((string)$line);
        if ($line === '' || strpos($line, '#') === 0) {
            return;
        }

        if (strpos($line, 'export ') === 0) {
            $line = trim(substr($line, 7));
        }

        $separator = strpos($line, '=');
        if ($separator === false) {
            return;
        }

        $name = trim(substr($line, 0, $separator));
        $value = trim(substr($line, $separator + 1));

        if ($name === '' || !preg_match('/^[A-Z0-9_]+$/i', $name)) {
            return;
        }

        if (!$overrideExisting && static::isDefined($name)) {
            return;
        }

        $value = static::normalizeValue($value);
        static::set($name, $value);
    }

    protected static function normalizeValue($value)
    {
        $value = trim((string)$value);
        $length = strlen($value);
        if ($length >= 2) {
            $first = $value[0];
            $last = $value[$length - 1];
            if (($first === '"' && $last === '"') || ($first === '\'' && $last === '\'')) {
                $value = substr($value, 1, -1);
            }
        }

        return str_replace(array('\n', '\r', '\t'), array("\n", "\r", "\t"), $value);
    }

    protected static function set($name, $value)
    {
        putenv($name . '=' . $value);
        $_ENV[$name] = $value;
        $_SERVER[$name] = $value;
    }

    protected static function isDefined($name)
    {
        return getenv($name) !== false || isset($_ENV[$name]) || isset($_SERVER[$name]);
    }
}
