<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Service;

use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class OpenAiClient
{
    public function __construct(
        private readonly HttpClientInterface $httpClient,
        #[Autowire(env: 'OPENAI_API_KEY')]
        private readonly string $apiKey,
    ) {
    }

    public function generatePrompt(string $context): string
    {
        $response = $this->httpClient->request('POST', 'https://api.openai.com/v1/chat/completions', [
            'headers' => [
                'Authorization' => 'Bearer '.$this->apiKey,
                'Content-Type' => 'application/json',
            ],
            'json' => [
                'model' => 'gpt-4o-mini',
                'messages' => [
                    ['role' => 'system', 'content' => 'Du bist ein Assistent, der Bild-Prompts für ein Ferienprogramm für Kinder (Ferienpass) erstellt. Der Prompt sollte für die Erstellung eines hochwertigen, freundlichen und ansprechenden Bildes für Kinder und Eltern eignen. Fügen Sie keinen Text in das Bild ein. Gebe NUR den Prompt zurück.'],
                    ['role' => 'user', 'content' => "Erstelle einen Bild-Prompt für das folgende Angebot: $context"],
                ],
                'temperature' => 0.7,
            ],
        ]);

        $data = $response->toArray(false);

        if (!isset($data['choices'][0]['message']['content'])) {
            throw new \RuntimeException('Unexpected OpenAI API response for prompt generation: '.json_encode($data));
        }

        return $data['choices'][0]['message']['content'];
    }

    public function generateImage(string $prompt): string
    {
        $response = $this->httpClient->request('POST', 'https://api.openai.com/v1/images/generations', [
            'headers' => [
                'Authorization' => 'Bearer '.$this->apiKey,
                'Content-Type' => 'application/json',
            ],
            'json' => [
                'model' => 'gpt-image-1.5',
                'prompt' => $prompt,
                'output_compression' => 70,
                'output_format' => 'jpeg',
            ],
            'timeout' => 300,
        ]);

        $data = $response->toArray(false);

        if (!isset($data['data'][0]['b64_json'])) {
            throw new \RuntimeException('Unexpected OpenAI API response for image generation: '.json_encode($data));
        }

        return $data['data'][0]['b64_json'];
    }
}
