<?php
declare(strict_types=1);

namespace App\Infrastructure\AI;

use App\Domain\AI\AiModel;
use App\Domain\AI\AiProvider;
use App\Domain\AI\AiQueryHandlerInterface;
use App\Infrastructure\AI\GPT4All\Gpt4AllQueryHandler;
use App\Infrastructure\AI\Ollama\OllamaQueryHandler;
use App\Infrastructure\AI\OpenAI\OpenAiQueryHandler;
use App\Framework\HttpClient\HttpClient;
use InvalidArgumentException;

final readonly class AiHandlerFactory
{
    public function __construct(
        private HttpClient $httpClient,
        private string $openAiApiKey = '',
        private string $gpt4AllApiUrl = 'http://host.docker.internal:4891',
        private string $ollamaApiUrl = 'http://host.docker.internal:11434'
    ) {}

    public function createForModel(AiModel $model): AiQueryHandlerInterface
    {
        return match($model->getProvider()) {
            AiProvider::OPENAI => new OpenAiQueryHandler(
                $this->httpClient,
                $this->openAiApiKey
            ),
            AiProvider::GPT4ALL => new Gpt4AllQueryHandler(
                $this->httpClient,
                $this->gpt4AllApiUrl
            ),
            AiProvider::OLLAMA => new OllamaQueryHandler(
                $this->httpClient,
                $this->ollamaApiUrl
            ),
            default => throw new InvalidArgumentException("Unsupported AI provider: {$model->getProvider()->value}")
        };
    }

    public function createForProvider(AiProvider $provider): AiQueryHandlerInterface
    {
        return match($provider) {
            AiProvider::OPENAI => new OpenAiQueryHandler(
                $this->httpClient,
                $this->openAiApiKey
            ),
            AiProvider::GPT4ALL => new Gpt4AllQueryHandler(
                $this->httpClient,
                $this->gpt4AllApiUrl
            ),
            AiProvider::OLLAMA => new OllamaQueryHandler(
                $this->httpClient,
                $this->ollamaApiUrl
            ),
            default => throw new InvalidArgumentException("Unsupported AI provider: {$provider->value}")
        };
    }

    public function getAvailableProviders(): array
    {
        $providers = [];

        // OpenAI ist verfügbar wenn API Key gesetzt ist
        if (!empty($this->openAiApiKey)) {
            $providers[] = AiProvider::OPENAI;
        }

        // GPT4All prüfen
        $gpt4allHandler = new Gpt4AllQueryHandler($this->httpClient, $this->gpt4AllApiUrl);
        if ($gpt4allHandler->isAvailable()) {
            $providers[] = AiProvider::GPT4ALL;
        }

        // Ollama prüfen
        $ollamaHandler = new OllamaQueryHandler($this->httpClient, $this->ollamaApiUrl);
        if ($ollamaHandler->isAvailable()) {
            $providers[] = AiProvider::OLLAMA;
        }

        return $providers;
    }

    public function getAvailableModels(): array
    {
        $availableProviders = $this->getAvailableProviders();
        $providerSet = array_flip($availableProviders);
        $availableModels = [];

        foreach (AiModel::cases() as $model) {
            if (isset($providerSet[$model->getProvider()->value])) {
                // Für Ollama zusätzlich prüfen ob das spezifische Modell verfügbar ist
                if ($model->getProvider() === AiProvider::OLLAMA) {
                    $ollamaHandler = new OllamaQueryHandler($this->httpClient, $this->ollamaApiUrl);
                    $ollamaModels = $ollamaHandler->getAvailableModels();
                    if (in_array($model->value, $ollamaModels, true)) {
                        $availableModels[] = $model;
                    }
                } else {
                    $availableModels[] = $model;
                }
            }
        }

        return $availableModels;
    }

    public function isProviderAvailable(AiProvider $provider): bool
    {
        return in_array($provider, $this->getAvailableProviders(), true);
    }

    public function getOllamaAvailableModels(): array
    {
        if (!$this->isProviderAvailable(AiProvider::OLLAMA)) {
            return [];
        }

        $ollamaHandler = new OllamaQueryHandler($this->httpClient, $this->ollamaApiUrl);
        return $ollamaHandler->getAvailableModels();
    }
}
