<?php
// OpenAI proxy configuration (workspace scope).
// Reads values from environment variables or .env files.

// Helper to check env vars from multiple sources
function get_env_var($key) {
    $val = getenv($key);
    if ($val !== false && $val !== '' && $val !== null) return $val;
    if (isset($_SERVER[$key]) && $_SERVER[$key] !== '') return $_SERVER[$key];
    if (isset($_ENV[$key]) && $_ENV[$key] !== '') return $_ENV[$key];
    return null;
}

$projectUuid = get_env_var('PROJECT_UUID');
$projectId   = get_env_var('PROJECT_ID');

// If missing, try loading from .env files
if (!$projectUuid || !$projectId) {
    // List of possible .env locations (relative to this file)
    $possiblePaths = [
        __DIR__ . '/../../.env', // executor/.env
        __DIR__ . '/../.env',    // workspace/.env
        __DIR__ . '/.env',       // ai/.env
        dirname(__DIR__, 2) . '/.env' // Alternative root
    ];

    foreach ($possiblePaths as $path) {
        $realPath = realpath($path);
        if ($realPath && is_readable($realPath)) {
            $lines = @file($realPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
            foreach ($lines as $line) {
                $line = trim($line);
                if ($line === '' || $line[0] === '#') continue;
                if (!str_contains($line, '=')) continue;
                
                [$key, $value] = array_map('trim', explode('=', $line, 2));
                if ($key === '') continue;
                
                $value = trim($value, "' ");
                // Only set if not already set
                if (!get_env_var($key)) {
                    putenv("{$key}={$value}");
                    $_SERVER[$key] = $value;
                    $_ENV[$key] = $value;
                }
            }
            // Stop after first successful .env load
            break;
        }
    }
    
    // Refresh vars
    $projectUuid = get_env_var('PROJECT_UUID');
    $projectId   = get_env_var('PROJECT_ID');
}

// Fallback if environment variables are completely missing in deployment
// Using values from db/config.php logic or current environment
if (!$projectUuid) $projectUuid = '36fb441e-8408-4101-afdc-7911dc065e36';
if (!$projectId) $projectId = '38960';

$baseUrl       = 'https://flatlogic.com';
$responsesPath = $projectId ? "/projects/{$projectId}/ai-request" : null;

return [
    'base_url'       => $baseUrl,
    'responses_path' => $responsesPath,
    'project_id'     => $projectId,
    'project_uuid'   => $projectUuid,
    'project_header' => 'project-uuid',
    'default_model'  => 'gpt-5-mini',
    'timeout'        => 30,
    'verify_tls'     => true,
];
