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

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

if (
    ($projectUuid === false || $projectUuid === null || $projectUuid === '') ||
    ($projectId === false || $projectId === null || $projectId === '')
) {
    $envPath = realpath(__DIR__ . '/../../.env'); // executor/.env
    if ($envPath && is_readable($envPath)) {
        $lines = @file($envPath, 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, "\"' ");
            if (getenv($key) === false || getenv($key) === '') {
                putenv("{$key}={$value}");
            }
        }
        $projectUuid = getenv('PROJECT_UUID');
        $projectId   = getenv('PROJECT_ID');
    }
}

$projectUuid = ($projectUuid === false) ? null : $projectUuid;
$projectId   = ($projectId === false) ? null : $projectId;

// Allow overriding with custom OpenAI settings
$openAiApiKey = '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';
$openAiBaseUrl = getenv('OPENAI_BASE_URL');

$isCustom = !empty($openAiApiKey);

if ($isCustom) {
    // Using custom OpenAI key, target OpenAI API directly
    $baseUrl = !empty($openAiBaseUrl) ? $openAiBaseUrl : 'https://api.openai.com/v1';
    $responsesPath = '/chat/completions'; // Standard for chat completions
    $headers = [
        'Authorization: Bearer ' . $openAiApiKey,
        'Content-Type: application/json',
    ];
} else {
    // Using Flatlogic proxy
    $baseUrl = 'https://flatlogic.com';
    $responsesPath = $projectId ? "/projects/{$projectId}/ai-request" : null;
    $headers = [
        'Content-Type: application/json',
    ];
    if ($projectUuid) {
        $headers[] = 'project-uuid: ' . $projectUuid;
    }
}

return [
    'base_url'       => $baseUrl,
    'responses_path' => $responsesPath,
    'headers'        => $headers,
    'is_custom'      => $isCustom,
    'project_id'     => $projectId,
    'project_uuid'   => $projectUuid,
    'project_header' => 'project-uuid',
    'default_model'  => 'gpt-3.5-turbo', // A more standard model
    'timeout'        => 30,
    'verify_tls'     => true,
];
