<?php

namespace Limb_Chatbot\Includes\AI_Providers\Gemini\Endpoints\Embed_Content\Handlers;

use Limb_Chatbot\Includes\Data_Objects\Vector;
use Limb_Chatbot\Includes\AI_Providers\Gemini\Handlers\Response_Handler;

/**
 * Class Embed_Content_Response_Handler
 *
 * Handles the response for embedding content requests in Gemini AI Provider.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Gemini\Endpoints\Embed_Content\Handlers
 * @since 1.0.0
 */
class Embed_Content_Response_Handler extends Response_Handler {

	/**
	 * The vector which should be returned
	 *
	 * @var Vector
	 * @since 1.0.0
	 */
	public Vector $vector;

	/**
	 * Embed_Content_Response_Handler constructor.
	 *
	 * @param  mixed  $response  HTTP response.
	 * @param  mixed  $http_client  HTTP client instance.
	 * @param  int  $dimension  HTTP client instance.
	 * @param  mixed|null  $endpoint  Optional endpoint reference.
	 * @param  mixed|null  $stream_parser  Optional stream parser instance.
	 *
	 * @since 1.0.0
	 */
	public function __construct( $response, $http_client, int $dimension, $endpoint = null, $stream_parser = null ) {
		parent::__construct( $response, $http_client, $endpoint, $stream_parser );
		$this->vector = $this->vector_factory( $dimension );
	}

	/**
	 * Factory method to create Vector from response body.
	 *
	 * @param  int  $dimension
	 *
	 * @return Vector
	 */
	public function vector_factory( int $dimension ): Vector {
		if ( empty( $this->get_body()->embedding ) || is_string( $this->get_body() ) ) {
			return Vector::make( [] );
		}
		return Vector::make( [ 'values' => array_slice( $this->get_body()->embedding->values, 0, $dimension ) ] );
	}

	/**
	 * Get the embedded Vector object.
	 *
	 * @return Vector|null
	 * @since 1.0.0
	 */
	public function get_vector(): ?Vector {
		return $this->vector;
	}
}