<?php

namespace Limb_Chatbot\Includes\AI_Providers\Gemini\Endpoints\Token;

use Limb_Chatbot\Includes\AI_Providers\Gemini\Services\Message_Service;
use Limb_Chatbot\Includes\AI_Providers\Gemini\Endpoints\Gemini_Endpoint;
use Limb_Chatbot\Includes\AI_Providers\Gemini\Handlers\Response_Handler;
use Limb_Chatbot\Includes\AI_Providers\Gemini\Utilities\Token_Utility;
use Limb_Chatbot\Includes\Exceptions\Exception;

/**
 * Class Token_Endpoint
 *
 * Handles token counting operations using Gemini API.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Gemini\Endpoints\Token
 * @since 1.0.0
 */
class Token_Endpoint extends Gemini_Endpoint {

	/**
	 * Token_Endpoint constructor.
	 *
	 * @param  Token_Utility  $utility  Token utility instance.
	 *
	 * @since 1.0.0
	 */
	public function __construct( Token_Utility $utility ) {
		parent::__construct( $utility );
	}

	/**
	 * Sends a request to the Gemini API to count the number of tokens used in a message.
	 *
	 * @return mixed API response body.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function count() {
		$args        = [
			'body'    => wp_json_encode( array(
				'contents' => [
					( new Message_Service() )->prepare_message( $this->utility->get_message() )
				],
			) ),
			'headers' => $this->get_header(),
		];
		$http_client = $this->http_client_factory();
		$response    = $http_client->post( $this->endpoint(), $args );

		return ( new Response_Handler( $response, $http_client, $this ) )->get_body();
	}

	/**
	 * Generate the full API endpoint URL for token counting.
	 *
	 * @return string Full URL for the token counting endpoint.
	 * @throws Exception
	 * @since 1.0.0
	 */
	private function endpoint() {
		return self::API_BASE_URL . $this->utility->get_version() . '/models/' . $this->utility->get_model_name() . ':countTokens?key=' . $this->get_auth_key( $this->utility->get_config() );
	}
}