<?php

namespace OtomaticAi\Api\Anthropic;

use Exception;
use OtomaticAi\Api\Anthropic\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 anthropic api endpoint
     *
     * @var string
     */
    private string $endpoint = "https://api.anthropic.com/v1";

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

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

        // create the http client
        $settings = [
            "base_uri" => rtrim($this->endpoint, "/") . '/',
            "headers" => [
                "x-api-key" => $key,
                "Content-Type" => "application/json",
                "Anthropic-Version" => "2023-06-01",
            ],
            "timeout" => 450,
            "connect_timeout" => 10
        ];

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

    /**
     * Call the messages api from anthropic
     *
     * @param array $payload
     * @return array
     * @throws Exception
     */
    public function messages(array $payload): array
    {
        // call the messages api
        $complete = $this->request("POST", "messages", [
            "json" => $payload
        ]);

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

        return $complete;
    }

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