<?php

declare(strict_types=1);

/**
 * Carga variables de entorno (.env) antes del contenedor DI.
 */

function apimodel_env_file_candidates(string $projectRoot): array
{
    $extra = trim((string) ($_SERVER['APIMODEL_ENV_FILE'] ?? getenv('APIMODEL_ENV_FILE') ?: ''));
    $list = [];
    if ($extra !== '') {
        $list[] = $extra;
    }
    $list[] = $projectRoot . '/.env';

    return $list;
}

function apimodel_load_env_fallback(string $envPath): void
{
    if (! is_file($envPath)) {
        return;
    }
    $lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (! is_array($lines)) {
        return;
    }
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#')) {
            continue;
        }
        $pos = strpos($line, '=');
        if ($pos === false) {
            continue;
        }
        $key = trim(substr($line, 0, $pos));
        $value = trim(substr($line, $pos + 1));
        if ($key === '') {
            continue;
        }
        if (
            (str_starts_with($value, '"') && str_ends_with($value, '"')) ||
            (str_starts_with($value, "'") && str_ends_with($value, "'"))
        ) {
            $value = substr($value, 1, -1);
        }
        if (getenv($key) === false) {
            putenv($key . '=' . $value);
            $_ENV[$key] = $value;
            $_SERVER[$key] = $value;
        }
    }
}

function apimodel_load_dotenv(string $projectRoot): void
{
    $candidates = apimodel_env_file_candidates($projectRoot);
    if (class_exists(\Dotenv\Dotenv::class)) {
        $loaded = false;
        foreach ($candidates as $envPath) {
            if (! is_file($envPath)) {
                continue;
            }
            \Dotenv\Dotenv::createImmutable(dirname($envPath), basename($envPath))->safeLoad();
            $loaded = true;
            break;
        }
        if (! $loaded) {
            \Dotenv\Dotenv::createImmutable($projectRoot)->safeLoad();
        }
    } else {
        foreach ($candidates as $envPath) {
            if (is_file($envPath)) {
                apimodel_load_env_fallback($envPath);
                break;
            }
        }
    }
}
