<?php
declare(strict_types=1);

namespace Celena\Core\Ai\Provider;

use Celena\Core\Ai\ProviderInterface;
use RuntimeException;

final class OpenAiProvider implements ProviderInterface
{
    public function __construct(
        private readonly string $apiKey,
        private readonly string $model = 'gpt-4o-mini',
    ) {
    }

    public function name(): string { return 'openai'; }

    public function complete(string $system, string $user, array $opts = []): string
    {
        $payload = [
            'model' => $opts['model'] ?? $this->model,
            'messages' => [
                ['role' => 'system', 'content' => $system],
                ['role' => 'user', 'content' => $user],
            ],
            'max_tokens' => (int) ($opts['max_tokens'] ?? 1024),
        ];
        if (isset($opts['temperature'])) {
            $payload['temperature'] = (float) $opts['temperature'];
        }

        $ch = curl_init('https://api.openai.com/v1/chat/completions');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $this->apiKey,
            ],
            CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
            CURLOPT_TIMEOUT => 60,
        ]);
        $body = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $err = curl_error($ch);
        curl_close($ch);

        if ($body === false) {
            throw new RuntimeException('OpenAI request failed: ' . $err);
        }
        $data = json_decode((string) $body, true);
        if ($status >= 400) {
            $msg = is_array($data) ? ($data['error']['message'] ?? (string) $body) : (string) $body;
            throw new RuntimeException('OpenAI error ' . $status . ': ' . $msg);
        }
        return trim((string) ($data['choices'][0]['message']['content'] ?? ''));
    }
}
