<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Ai\Endpoints\Embedding\Handlers;

use Limb_Chatbot\Includes\Data_Objects\Token_Usage;
use Limb_Chatbot\Includes\Data_Objects\Vector;
use Limb_Chatbot\Includes\AI_Providers\Open_Ai\Handlers\Response_Handler;

/**
 * Class Embedding_Response_Handler
 *
 * Parses and handles the response from an OpenAI Embedding API request.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Ai\Endpoints\Embedding\Handlers
 * @since 1.0.0
 */
class Embedding_Response_Handler extends Response_Handler {

	/**
	 * The vector resulting from the embedding response.
	 *
	 * @var Vector|null
	 */
	protected ?Vector $vector = null;

	/**
	 * Parses the HTTP response and sets the vector result if no error occurred.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function parse() {
		parent::parse();
		if ( ! $this->has_error() ) {
			$this->set_vector( $this->vector_factory() );
		}
	}

	/**
	 * Returns the parsed Vector object from the response.
	 *
	 * @return Vector
	 * @since 1.0.0
	 */
	public function get_vector(): Vector {
		return $this->vector;
	}

	/**
	 * Sets the vector object.
	 *
	 * @param Vector $vector
	 * @return void
	 * @since 1.0.0
	 */
	public function set_vector( Vector $vector ): void {
		$this->vector = $vector;
	}

	/**
	 * Creates a Vector object from the embedding API response.
	 *
	 * @return Vector
	 * @since 1.0.0
	 */
	protected function vector_factory(): Vector {
		$vector = Vector::make();
		if ( ! empty( $this->get_body()->data ) && ! empty( $this->get_body()->data[0] ) && ! empty( $this->get_body()->data[0]->embedding ) ) {
			$values = $this->get_body()->data[0]->embedding;
			$vector->set_values( $values );
			$vector->set_dimension( count( $values ) );
			if ( ! empty( $this->get_body() ) && $usage = $this->get_body()->usage ) {
				$usage_data = [
					'input_tokens'  => $usage->prompt_tokens,
					'output_tokens' => 0,
				];
				$vector->set_usage( Token_Usage::make( $usage_data ) );
			}
		}

		return $vector;
	}
}
