<?php

namespace Kanews\Kai\AI;

use Kanews\Kai\AI\Providers\GeminiProvider;
use Kanews\Kai\AI\Providers\OpenAIProvider;
use Kanews\Kai\Support\Options;

class Client
{
    /**
     * @var array<string,ProviderInterface>
     */
    private $providers = [];

    public function __construct()
    {
        $this->providers = [
            'openai' => new OpenAIProvider(),
            'gemini' => new GeminiProvider(),
        ];
    }

    public function chat(string $task, array $context = []): array
    {
        $prompt   = PromptFactory::build($task, $context);
        $provider = $this->resolveProvider($task, $context['provider'] ?? null);

        return $provider->chat($prompt);
    }

    public function availableProviders(): array
    {
        $choices = [];
        foreach ($this->providers as $key => $provider) {
            if ($provider->hasCredentials()) {
                $choices[] = $key;
            }
        }

        return $choices ?: ['openai'];
    }

    public function tts(string $text, string $voice = 'alloy')
    {
        $apiKey = Options::getApiKey('openai');
        if (empty($apiKey)) {
            throw new \RuntimeException(__('OpenAI API anahtarı bulunamadı.', 'kanews'));
        }

        $payload = [
            'model' => 'tts-1',
            'input' => substr($text, 0, 4090),
            'voice' => $voice ?: 'alloy',
        ];

        $response = wp_remote_post('https://api.openai.com/v1/audio/speech', [
            '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 = wp_remote_retrieve_body($response);
        if (empty($body)) {
            throw new \RuntimeException(__('Boş TTS yanıtı alındı.', 'kanews'));
        }

        return $body;
    }

    private function resolveProvider(string $task, ?string $requested): ProviderInterface
    {
        $preferred   = $requested ?: Options::getDefaultProvider();
        $providerKey = apply_filters('kanews_kai_provider_for_task', $preferred, $task, $requested);

        // If a specific provider is explicitly requested, enforce it; otherwise treat preferred as best-effort.
        if ($providerKey && isset($this->providers[$providerKey])) {
            if ($this->providers[$providerKey]->hasCredentials()) {
                return $this->providers[$providerKey];
            }
            if ($requested) {
                throw new \RuntimeException(
                    sprintf(
                        __('Seçilen yapay zekâ sağlayıcısı (%s) yapılandırılmamış. Lütfen API anahtarını kontrol edin.', 'kanews'),
                        $providerKey
                    )
                );
            }
        }

        // Fallback: use first available provider with credentials
        foreach ($this->providers as $key => $provider) {
            if ($provider->hasCredentials()) {
                return $provider;
            }
        }

        throw new \RuntimeException(__('Hiçbir yapay zekâ sağlayıcısı yapılandırılmamış.', 'kanews'));
    }
}

