<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints;

use Limb_Chatbot\Includes\Data_Objects\Vector;
use Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints\Embedding\Embedding_Response_Handler;
use Limb_Chatbot\Includes\Exceptions\Exception;
use Limb_Chatbot\Includes\Services\Helper;

/**
 * Class Embedding_Endpoint
 *
 * Handles the OpenRouter Embedding API requests and responses.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints
 * @since 1.0.14
 */
class Embedding_Endpoint extends Open_Router_Endpoint {

	/**
	 * Embedding_Endpoint constructor.
	 *
	 * @param mixed $utility Utility object containing configuration for the request.
	 * @since 1.0.14
	 */
	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.14
	 */
	public function generate( Vector $vector ) {

		$http_client = $this->http_client_factory();
		$model = $vector->get_ai_model();
		$body        = [
			'model' => $model->get_name(),
			'input' => $vector->get_input(),
		];
		if ( ! empty( $model->get_endpoints()['embeddings']['dimensions'] ) && count( $model->get_endpoints()['embeddings']['dimensions'] ) > 1 ) {
			$body['dimensions'] = $vector->get_dimension();
		}
		if ( $this->utility->get_encoding_format() ) {
			$body['encoding_format'] = $this->utility->get_encoding_format();
		}

		$response = $http_client->post( self::API_BASE_URL . '/embeddings', array(
			'headers' => $this->get_header( $vector->get_config() ),
			'body'    => json_encode( $body ),
			'timeout' => $this->utility->get_timeout(),
		) );


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