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

function get_ai_env($key) {
    $val = getenv($key);
    if ($val !== false && $val !== '') {
        error_log("get_ai_env: $key from getenv: " . substr($val, 0, 5) . "...");
        return $val;
    }
    if (isset($_ENV[$key]) && $_ENV[$key] !== '') {
        error_log("get_ai_env: $key from \$_ENV: " . substr($_ENV[$key], 0, 5) . "...");
        return $_ENV[$key];
    }
    if (isset($_SERVER[$key]) && $_SERVER[$key] !== '') {
        error_log("get_ai_env: $key from \$_SERVER: " . substr($_SERVER[$key], 0, 5) . "...");
        return $_SERVER[$key];
    }
    error_log("get_ai_env: $key not found in environment");
    return null;
}

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

if (!$projectUuid || !$projectId) {
    error_log("PROJECT_UUID or PROJECT_ID missing, starting .env search");
    $possiblePaths = [
        __DIR__ . '/../../.env',
        __DIR__ . '/../.env',
        __DIR__ . '/.env',
        '/home/ubuntu/executor/.env',
        '/var/www/html/.env'
    ];
    
    foreach ($possiblePaths as $path) {
        if (file_exists($path) && is_readable($path)) {
            error_log("Trying .env path: $path");
            $env = @parse_ini_file($path);
            if ($env) {
                if (!$projectUuid && !empty($env['PROJECT_UUID'])) {
                    $projectUuid = $env['PROJECT_UUID'];
                    error_log("Found PROJECT_UUID in $path: " . substr($projectUuid, 0, 5) . "...");
                }
                if (!$projectId && !empty($env['PROJECT_ID'])) {
                    $projectId = $env['PROJECT_ID'];
                    error_log("Found PROJECT_ID in $path: " . $projectId);
                }
            } else {
                error_log("Failed to parse_ini_file: $path");
            }
        } else {
            error_log("Path not found or not readable: $path");
        }
        if ($projectUuid && $projectId) break;
    }
} else {
    error_log("PROJECT_UUID and PROJECT_ID found in environment immediately.");
}

$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-4o-mini',
    'timeout'        => 30,
    'verify_tls'     => true,
];
