<?php

namespace Limb_Chatbot\Includes\Vector_Dbs\Pinecone\Endpoints;

use Limb_Chatbot\Includes\Data_Objects\Vector_Index;
use Limb_Chatbot\Includes\Exceptions\Error_Codes;
use Limb_Chatbot\Includes\Exceptions\Exception;
use Limb_Chatbot\Includes\Services\Endpoint;
use Limb_Chatbot\Includes\Data_Objects\Config;

/**
 * Class Pinecone_Endpoint
 *
 * Base class for Pinecone API endpoints.
 *
 * @package Limb_Chatbot\Includes\Vector_Dbs\Pinecone\Endpoints
 *
 * @since 1.0.0
 */
class Pinecone_Endpoint extends Endpoint {

	/**
	 * Base URL for Pinecone API.
	 *
	 * @var string
	 * @since 1.0.0
	 */
	const API_BASE_URL = 'https://api.pinecone.io/';

	/**
	 * Get HTTP headers required for Pinecone API requests.
	 *
	 * @param bool $beta_version Optional flag to use beta version headers (currently unused).
	 * @return array<string,string> Associative array of HTTP headers.
	 *
	 * @throws Exception Throws if API key is missing in the config.
	 *
	 * @since 1.0.0
	 */
	protected function get_header( $beta_version = false ) {
		$config = $this->get_config();
		if ( empty( $config ) || ! ( $config instanceof Config ) || empty( $config->get_params()['api_key'] ) ) {
			throw new Exception( Error_Codes::AUTHENTICATION_API_KEY_MISSING, __( 'Api key is missing', 'limb-chatbot' ) );
		}

		return array(
			'Api-Key'      => $config->get_params()['api_key'],
			'Content-Type' => 'application/json'
		);
	}

	/**
	 * Defines the API host for the endpoint based on the vector index meta.
	 *
	 * @param Vector_Index $vector_index Vector index object to retrieve host from.
	 *
	 * @return void
	 *
	 * @throws Exception Throws if the 'host' meta value is missing or empty.
	 *
	 * @since 1.0.0
	 * @since 1.0.15 Added host define by dimension
	 */
	protected function define_host( Vector_Index $vector_index ) {
		if ( ! empty( $this->utility ) && method_exists( $this->utility, 'get_dimension' ) ) {
			$meta_key  = 'host_' . $this->utility->get_dimension();
			$host_meta = $vector_index->find_meta( $meta_key );
			if ( $host_meta ) {
				if ( ! empty( $host_meta->get_meta_value() ) ) {
					$this->host = $host_meta->get_meta_value();
					return;
				}
				throw new Exception( Error_Codes::MISSING_VALUE, __( 'Host for dimension ' . $this->utility->get_dimension() . ' is empty', 'limb-chatbot' ) );
			}
		}

		if ( ! ( $host_meta = $vector_index->find_meta( 'host' ) ) || empty( $host_meta->get_meta_value() ) ) {
			throw new Exception( Error_Codes::MISSING_VALUE, __( 'Host is empty', 'limb-chatbot' ) );
		}
		$this->host = $host_meta->get_meta_value();
	}
}