<?php

namespace App\Core\Ai\Services;

use App\Core\Settings\Services\SettingService;
use OpenAI;
use Throwable;

class OpenAiProvider
{
    public function send(string $prompt, string $model): array
    {
        $apiKey = (string) ((new SettingService())->get('openai.api_key') ?: env('openai.api_key'));

        if ($apiKey === '') {
            return [
                'status' => 'stub',
                'response' => 'OpenAI n’est pas encore configuré. Ajoutez openai.api_key dans les paramètres Core ou dans le fichier .env.',
                'tokens_input' => null,
                'tokens_output' => null,
            ];
        }

        try {
            $response = OpenAI::client($apiKey)->chat()->create([
                'model' => $model,
                'messages' => [
                    ['role' => 'system', 'content' => 'You are the generic AI engine of ONE CORE.'],
                    ['role' => 'user', 'content' => $prompt],
                ],
            ]);

            return [
                'status' => 'success',
                'response' => $response->choices[0]->message->content ?? '',
                'tokens_input' => $response->usage->promptTokens ?? null,
                'tokens_output' => $response->usage->completionTokens ?? null,
            ];
        } catch (Throwable $e) {
            return [
                'status' => 'error',
                'response' => null,
                'tokens_input' => null,
                'tokens_output' => null,
                'error_message' => $e->getMessage(),
            ];
        }
    }
}
