<?php

namespace OtomaticAi\Api\Gemini;

use Exception;
use OtomaticAi\Api\Gemini\Exceptions\ApiException;
use OtomaticAi\Models\Usages\Usage;
use OtomaticAi\Utils\Settings;
use OtomaticAi\Vendors\Illuminate\Support\Arr;
use OtomaticAi\Vendors\GuzzleHttp\Client as HttpClient;
use OtomaticAi\Vendors\GuzzleHttp\Exception\ClientException;

class Client
{
    /**
     * The api endpoint
     *
     * @var string
     */
    private string $endpoint = "https://generativelanguage.googleapis.com/v1beta/models";

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

    /**
     * The api key
     *
     * @var string
     */
    private string $key;

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

        $this->key = $key;

        // create the http client
        $settings = [
            "base_uri" => rtrim($this->endpoint, "/") . '/',
            "headers" => [
                "Content-Type" => "application/json",
            ],
            "timeout" => 600
        ];

        $this->client = new HttpClient($settings);
    }

    /**
     * Call the list models api from gemini
     *
     * @return array
     * @throws Exception
     */
    public function listModels(): array
    {
        return $this->request("GET", "", [
            "query" => [
                "key" => $this->key
            ]
        ]);
    }

    /**
     * Call the chat api
     *
     * @param array $payload
     * @return array
     * @throws Exception
     */
    public function chat(array $payload): array
    {

        // call the messages api
        $complete = $this->request("POST", rtrim($this->endpoint, "/") . '/' . $payload["model"] . ":generateContent", [
            "query" => [
                "key" => $this->key
            ],
            "json" => $payload
        ]);

        // store the usage
        $usage = Arr::get($complete, "usageMetadata", []);
        if (Arr::get($usage, 'promptTokenCount', 0) + Arr::get($usage, 'candidatesTokenCount', 0) > 0) {
            Usage::create([
                "provider" => "gemini_chat",
                "payload" => [
                    "model" => Arr::get($complete, 'modelVersion'),
                    "input_tokens" => Arr::get($usage, 'promptTokenCount', 0),
                    "output_tokens" => Arr::get($usage, 'candidatesTokenCount', 0),
                ]
            ]);
        }

        return $complete;
    }

    /**
     * Call the image api
     *
     * @param array $payload
     * @return array
     * @throws Exception
     */
    public function image(array $payload): array
    {
        $response = $this->request("POST", rtrim($this->endpoint, "/") . '/' . $payload["model"] . ":generateContent", [
            "query" => [
                "key" => $this->key
            ],
            "json" => $payload
        ]);

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

        return $response;
    }

    static public function getImageInlineData($result)
    {
        $parts = Arr::get($result, "candidates.0.content.parts");

        $part = Arr::first($parts, function ($part) {
            return Arr::get($part, "inlineData.data") !== null;
        });

        if (!empty($part)) {
            return Arr::get($part, "inlineData.data");
        }

        return null;
    }

    /**
     * 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;
        }
    }
}
