<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints\Embedding;

use Limb_Chatbot\Includes\AI_Providers\Open_Router\Handlers\Response_Handler;
use Limb_Chatbot\Includes\Data_Objects\Token_Usage;
use Limb_Chatbot\Includes\Data_Objects\Vector;
use Limb_Chatbot\Includes\Exceptions\Exception;

/**
 * Class Embedding_Response_Handler
 *
 * Handles parsing of OpenRouter embedding API responses.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints\Embedding
 * @since 1.0.14
 */
class Embedding_Response_Handler extends Response_Handler {

	public function parse() {
		parent::parse();
	}

	/**
	 * Retrieves the vector from the embedding response.
	 *
	 * @return Vector|null The vector with embedding data or null on failure.
	 * @throws Exception
	 * @since 1.0.14
	 */
	public function get_vector(): ?Vector {

		$body = $this->get_body();

		if ( empty( $body->data[0]->embedding ) ) {
			return null;
		}

		$vector = $this->endpoint->utility->global_utility->get_vector();

		// Set the embedding values and dimension
		$values = $body->data[0]->embedding;

		$vector->set_values( $values );
		$vector->set_dimension( count( $values ) );

		// Set token usage if available
		if ( ! empty( $body->usage ) ) {
			$usage_data = [
				'input_tokens'  => $body->usage->prompt_tokens ?? 0,
				'output_tokens' => 0, // Embedding endpoints typically don't have output tokens
			];
			$vector->set_usage( Token_Usage::make( $usage_data ) );
		}

		return $vector;
	}
}
