<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Ai\Endpoints;

use Limb_Chatbot\Includes\Data_Objects\Vector;
use Limb_Chatbot\Includes\AI_Providers\Open_Ai\Endpoints\Embedding\Handlers\Embedding_Response_Handler;
use Limb_Chatbot\Includes\Exceptions\Exception;

/**
 * Class Embedding_Endpoint
 *
 * Handles the OpenAI Embedding API requests and responses.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Ai\Endpoints
 * @since 1.0.0
 */
class Embedding_Endpoint extends Open_Ai_Endpoint {

	/**
	 * Embedding_Endpoint constructor.
	 *
	 * @param mixed $utility Utility object containing configuration for the request.
	 * @since 1.0.0
	 */
	public function __construct( $utility ) {
		parent::__construct( $utility );
	}

	/**
	 * Sends a request to generate an embedding from a given Vector object.
	 *
	 * @param  Vector  $vector  The vector object containing input and model metadata.
	 *
	 * @return Vector|null The resulting vector with embedding data or null on failure.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function generate( Vector $vector ) {
		$http_client = $this->http_client_factory();
		$response    = $http_client->post( self::API_BASE_URL . '/embeddings', array(
			'headers' => $this->get_header( $vector->get_config() ),
			'body'    => json_encode( [
				'model'           => $vector->get_ai_model()->get_name(),
				'input'           => $vector->get_input(),
				'encoding_format' => $this->utility->get_encoding_format(),
				'dimensions'      => $vector->get_dimension()
			] ),
			'timeout' => $this->utility->get_timeout(),
		) );

		return ( new Embedding_Response_Handler( $response, $http_client, $this ) )->get_vector();
	}
}