<?php

namespace Kanews\Kai\AI\Providers;

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

class GeminiProvider implements ProviderInterface
{
    public function id(): string
    {
        return 'gemini';
    }

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

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

        $textParts = [];
        foreach ($prompt['messages'] as $message) {
            $prefix = $message['role'] === 'system' ? 'Instruction:' : ucfirst($message['role']) . ':';
            $textParts[] = $prefix . ' ' . $message['content'];
        }
        $text = implode("\n\n", $textParts);

        // Use the correct Gemini model name
        // Prefer latest models when available
        $requestedModel = $prompt['model'] ?? 'gemini-2.5-flash';
        
        // Map OpenAI model names to Gemini equivalents
        $modelMap = [
            'gpt-4o' => 'gemini-2.5-flash',
            'gpt-4-turbo' => 'gemini-2.5-flash',
            'gpt-4' => 'gemini-2.5-flash',
            'gpt-4o-mini' => 'gemini-2.5-flash',
            'gpt-3.5-turbo' => 'gemini-2.5-flash',
        ];
        
        $model = $modelMap[$requestedModel] ?? $requestedModel;
        
        // Ensure we're using a valid Gemini model
        $validModels = [
            'gemini-2.5-flash',
            'gemini-1.5-flash',
            'gemini-1.5-flash-latest',
            'gemini-1.5-pro',
            'gemini-1.5-pro-latest',
            'gemini-pro',
        ];
        if (!in_array($model, $validModels, true)) {
            $model = 'gemini-2.5-flash'; // Fallback to default
        }
        
        // Gemini's latest models now live under v1 endpoint
        $apiVersion = 'v1';
        $endpoint = sprintf(
            'https://generativelanguage.googleapis.com/%s/models/%s:generateContent?key=%s',
            $apiVersion,
            rawurlencode($model),
            rawurlencode($apiKey)
        );

        $payload = [
            'contents' => [
                [
                    'parts' => [
                        ['text' => $text],
                    ],
                ],
            ],
        ];

        $response = wp_remote_post($endpoint, [
            'timeout' => 60,
            'headers' => [
                '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'])) {
            $message = $body['error']['message'] ?? __('Gemini API hatası', 'kanews');
            throw new \RuntimeException($message);
        }

        $content = '';
        if (!empty($body['candidates'][0]['content']['parts'])) {
            foreach ($body['candidates'][0]['content']['parts'] as $part) {
                if (!empty($part['text'])) {
                    $content .= $part['text'];
                }
            }
        }

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

