<?php

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

use Limb_Chatbot\Includes\AI_Providers\Open_Ai\Open_Ai;
use Limb_Chatbot\Includes\Data_Objects\File;
use Limb_Chatbot\Includes\Data_Objects\Meta_Data_Object;
use Limb_Chatbot\Includes\Data_Objects\Vector;
use Limb_Chatbot\Includes\AI_Providers\Open_Ai\Handlers\Response_Handler;
use Limb_Chatbot\Includes\Exceptions\Exception;

/**
 * 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 File_Response_Handler extends Response_Handler {

	/**
	 * Maps file metadata keys to response body keys.
	 *
	 * @var array
	 */
	private static $file_metadata_mapper = array(
		'external_id'         => 'id',
		'external_created_at' => 'created_at',
		'external_expires_at' => 'expires_at',
		'external_bytes'      => 'bytes',
	);

	/**
	 * 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
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function parse() {
		parent::parse();
	}

	/**
	 * Returns the file metadata as an array of Meta_Data_Object instances.
	 *
	 * @return Meta_Data_Object[]
	 * @since 1.0.0
	 */
	public function get_file_metadata() {
		$metadata = array(
			Meta_Data_Object::make( [
				'meta_key'   => 'external_status',
				'meta_value' => File::EXTERNAL_STATUS_ACTIVE,
			] ),
			Meta_Data_Object::make( [
				'meta_key'   => 'external_provider',
				'meta_value' => Open_Ai::$id,
			] )
		);
		$body     = $this->get_body();
		foreach ( self::$file_metadata_mapper as $meta_key => $body_key ) {
			if ( isset( $body->{$body_key} ) ) {
				$meta = new Meta_Data_Object();
				$meta->set_meta_key( $meta_key );
				$meta->set_meta_value( $body->{$body_key} );
				$metadata[] = $meta;
			}
		}

		return $metadata;
	}
}
