<?php

namespace Kanews\Kai\AI\Providers;

use Kanews\Kai\AI\ProviderInterface;
use Kanews\Kai\Support\Options;

class OpenAIProvider implements ProviderInterface
{
    public function id(): string
    {
        return 'openai';
    }

    public function hasCredentials(): bool
    {
        return !empty(Options::getApiKey('openai'));
    }

    public function chat(array $prompt): array
    {
        $apiKey = Options::getApiKey('openai');
        if (empty($apiKey)) {
            throw new \RuntimeException(__('OpenAI API anahtarı bulunamadı.', 'kanews'));
        }

        $payload = [
            'model'       => $prompt['model'] ?? 'gpt-4o-mini',
            'messages'    => $prompt['messages'],
            'temperature' => $prompt['temperature'] ?? 0.7,
        ];

        if (!empty($prompt['max_tokens'])) {
            $payload['max_tokens'] = (int) $prompt['max_tokens'];
        }

        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
            'timeout' => 60,
            'headers' => [
                'Authorization' => 'Bearer ' . $apiKey,
                'Content-Type'  => 'application/json',
            ],
            'body'    => wp_json_encode($payload, JSON_UNESCAPED_UNICODE),
        ]);

        if (is_wp_error($response)) {
            throw new \RuntimeException($response->get_error_message());
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        if (isset($body['error'])) {
            throw new \RuntimeException($body['error']['message'] ?? __('OpenAI API ERROR', 'kanews'));
        }

        $content = $body['choices'][0]['message']['content'] ?? '';

        return [
            'content' => trim((string) $content),
            'raw'     => $body,
        ];
    }
}

