<?php

declare(strict_types=1);

namespace KimaAI\Ai\Providers;

use InvalidArgumentException;
use KimaAI\Ai\Providers\Http\HttpClientInterface;
use KimaAI\Ai\Providers\OpenAI\OpenAiClient;
use KimaAI\Ai\Providers\OpenRouter\OpenRouterClient;
use KimaAI\Ai\Providers\Replicate\ReplicateClient;
use KimaAI\Ai\Providers\Ollama\OllamaClient;


final class Factory {

  public static function create(string $provider, string $api_key, ?string $organization = null, array $options = []): AbstractClient {
    $provider = strtolower($provider);
    $http_client = ($options['httpClient'] ?? null) instanceof HttpClientInterface ? $options['httpClient'] : null;

    return match ($provider) {
      'openai' => new OpenAiClient($api_key, $organization, $options['baseUrl'] ?? 'https://api.openai.com/v1', $http_client),
      'openrouter' => new OpenRouterClient(
        $api_key,
        $organization,
        $options['baseUrl'] ?? 'https://openrouter.ai/api/v1',
        $http_client,
        is_string($options['siteUrl'] ?? null) ? $options['siteUrl'] : null,
        is_string($options['siteName'] ?? null) ? $options['siteName'] : null
      ),
      'ollama' => new OllamaClient($api_key, $organization, $options['baseUrl'] ?? 'http://localhost:11434/v1', $http_client),
      'replicate' => new ReplicateClient($api_key, $options['baseUrl'] ?? 'https://api.replicate.com/v1', $http_client),
      default => self::unsupported($provider),
    };
  }

  private static function unsupported(string $provider): AbstractClient {
    $error_message = 'Unsupported provider: ' . $provider;
    if (class_exists('\KimaAI\Logger', false)) {
      \KimaAI\Logger::error($error_message);
    }
    throw new InvalidArgumentException($error_message);
  }
}
