<?php

namespace OtomaticAi\Api\Ideogram;

use Exception;
use OtomaticAi\Api\Ideogram\Exceptions\ApiException;
use OtomaticAi\Models\Usages\Usage;
use OtomaticAi\Utils\Settings;
use OtomaticAi\Vendors\GuzzleHttp\Client as HttpClient;
use OtomaticAi\Vendors\Illuminate\Support\Arr;
use OtomaticAi\Vendors\GuzzleHttp\Pool;
use OtomaticAi\Vendors\GuzzleHttp\Psr7\Request;
use OtomaticAi\Vendors\GuzzleHttp\Psr7\Response;

class PoolClient
{
    /**
     * The ideogram api endpoint
     *
     * @var string
     */
    private string $endpoint = "https://api.ideogram.ai";

    /**
     * The GuzzleHttp client
     *
     * @var HttpClient
     */
    private HttpClient $client;

    /**
     * The auth key
     *
     * @var HttpClient
     */
    private string $key;

    /**
     * Create a new StabilityAi Api client
     *
     * @param string|null $key
     * @throws Exception
     */
    function __construct(string $key = null)
    {
        // get the key
        if (empty($key)) {
            $key = Settings::get("api.ideogram.api_key");
        }
        if (empty($key)) {
            throw new Exception("No Ideogram Api Key provided.");
        }

        $this->key = $key;

        // create the http client
        $this->client = new HttpClient(
            [
                "base_uri" => rtrim($this->endpoint, "/") . '/',
                "headers" => [
                    "Api-Key" => $this->key,
                    "Accept" => "application/json",
                    "Content-Type" => "application/json",
                ],
                "timeout" => 600
            ]
        );
    }

    /**
     * Call the generate api endpoint
     *
     * @param array $settings
     * @return array
     * @throws Exception
     */
    public function generate(array $settings = []): array
    {
        $requests = [];
        foreach ($settings as $payload) {

            // make the payload
            $payload = array_merge([
                "rendering_speed" => "TURBO",
                "magic_prompt" => "AUTO",
                "resolution" => "1280x768",
            ], $payload);

            // make the request
            $requests[] = [
                "request" => new Request(
                    'POST',
                    "v1/ideogram-v3/generate",
                    [],
                    json_encode($payload)
                ),
                "after" => function ($complete) use ($payload) {

                    // store the usage
                    Usage::create([
                        "provider" => "ideogram",
                        "payload" => [
                            "model" => "ideogram-v3",
                            "quality" => $payload["rendering_speed"],
                            "artifacts" => 1,
                        ]
                    ]);
                }
            ];
        }

        // call the stability ai api
        $completes = $this->run($requests);

        return $completes;
    }

    /**
     * Perform an api request
     *
     * @param array $requests
     * @param stirng $uri
     * @param array $options
     * @return array
     * @throws Exception
     */
    private function run(array $requests)
    {
        $output = [];

        // get the http requests
        $httpRequests = Arr::pluck($requests, "request");

        // create the pool
        $pool = new Pool($this->client, $httpRequests, [
            'concurrency' => 10,
            'fulfilled' => function (Response $response, $index) use (&$output, $requests) {
                $response = $response->getBody()->getContents();
                $response = json_decode($response, true);
                $output[$index] = $response;

                // call after callback
                if (!empty($requests[$index]["after"]) && is_callable($requests[$index]["after"])) {
                    $requests[$index]["after"]($response);
                }
            },
            'rejected' => function (Exception $reason, $index) {
                $e = ApiException::make($reason);
                throw $e;
            },
        ]);

        // call the pool
        $promise = $pool->promise();
        $promise->wait();

        return $output;
    }
}
