<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints;

use Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints\Model\Handlers\Model_Response_Handler;
use Limb_Chatbot\Includes\AI_Providers\Open_Router\Utilities\AI_Model_Utility;
use Limb_Chatbot\Includes\Data_Objects\AI_Model;
use Limb_Chatbot\Includes\Exceptions\Exception;

/**
 * Class Model_Endpoint
 *
 * Handles API requests related to AI models such as listing models.
 *
 * Note: The /models endpoint is public and doesn't require authentication.
 * However, we still include API key if available for better rate limits.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints
 * @since 1.0.14
 */
class Model_Endpoint extends Open_Router_Endpoint {

	/**
	 * Constructor.
	 *
	 * @param AI_Model_Utility $utility Utility class instance used for configuration and helper methods.
	 * @since 1.0.14
	 */
	public function __construct( AI_Model_Utility $utility ) {
		parent::__construct( $utility );
	}

	/**
	 * Lists all available AI models from the OpenRouter API.
	 *
	 * Note: This endpoint is public and works without authentication.
	 *
	 * @return array The list of available AI models.
	 * @throws Exception
	 * @since 1.0.14
	 */
	public function list() {
		$http_client = $this->http_client_factory();
		$response    = $http_client->get( self::API_BASE_URL . '/models', array(
			'headers' => $this->get_public_header(),
			'timeout' => $this->utility->get_timeout(),
		) );

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

	/**
	 * Retrieves detailed information about a specific model.
	 *
	 * Note: This endpoint is public and works without authentication.
	 *
	 * @param  AI_Model  $model  The AI model to retrieve.
	 *
	 * @return AI_Model|null Retrieved model details.
	 * @throws Exception
	 * @since 1.0.14
	 */
	public function retrieve( AI_Model $model ) {
		$http_client = $this->http_client_factory();
		$response    = $http_client->get( self::API_BASE_URL . '/models/' . urlencode( $model->get_name() ), array(
			'headers' => $this->get_public_header(),
			'timeout' => $this->utility->get_timeout(),
		) );

		return ( new Model_Response_Handler( $response, $http_client, $this ) )->get_model();
	}


}
