<?php

namespace OtomaticAi\Api\Flux;

use Exception;
use OtomaticAi\Api\Ideogram\Exceptions\ApiException;
use OtomaticAi\Vendors\GuzzleHttp\Exception\ClientException;
use OtomaticAi\Models\Usages\Usage;
use OtomaticAi\Utils\Settings;
use OtomaticAi\Vendors\GuzzleHttp\Client as HttpClient;

class Client
{
    /**
     * The Flux api endpoint
     *
     * @var string
     */
    private string $endpoint = "https://api.bfl.ai/v1";

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

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

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

        $this->key = $key;

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

    /**
     * Call the create task api endpoint
     *
     * @param array $settings
     * @return array
     * @throws Exception
     */
    public function createTask(array $settings = []): array
    {
        // make the payload
        if ($settings["model"] === "flux-kontext-pro" || $settings["model"] === "flux-kontext-max") {
            $settings = array_merge([
                "aspect_ratio" => "21:9",
                "prompt_upsampling" => true,
            ], $settings);
        } else {
            $settings = array_merge([
                "width" => 1344,
                "height" => 768,
                "prompt_upsampling" => true,
            ], $settings);
        }

        // call the api endpoint
        $response = $this->request("POST", $settings["model"], [
            "json" => $settings
        ]);

        // store the usage
        Usage::create([
            "provider" => "flux",
            "payload" => [
                "model" => $settings["model"],
                "artifacts" => 1,
            ]
        ]);

        return $response;
    }

    /**
     * Call the get result api endpoint
     *
     * @param string $pollingUrl
     * @return array
     * @throws Exception
     */
    public function getResult(string $pollingUrl): array
    {
        // call the api endpoint
        $response = $this->request("GET", $pollingUrl);

        return $response;
    }

    /**
     * Perform an api request
     *
     * @param string $method
     * @param stirng $uri
     * @param array $options
     * @return array
     * @throws Exception
     */
    private function request(string $method, string $uri, array $options = [])
    {
        try {
            $response = $this->client->request($method, $uri, $options);
            $response = $response->getBody()->getContents();
            $response = json_decode($response, true);

            return $response;
        } catch (ClientException $e) {
            $e = ApiException::make($e);

            throw $e;
        }
    }
}
