<?php

namespace Limb_Chatbot\Includes\AI_Providers\Claude\Endpoints\Model;

use Limb_Chatbot\Includes\AI_Providers\Claude\Endpoints\Claude_Endpoint;
use Limb_Chatbot\Includes\AI_Providers\Claude\Endpoints\Model\Handlers\Model_Response_Handler;
use Limb_Chatbot\Includes\Data_Objects\AI_Model;
use Limb_Chatbot\Includes\Exceptions\Error_Codes;
use Limb_Chatbot\Includes\Exceptions\Exception;

/**
 * Class Model_Endpoint
 *
 * Handles model-related actions for Claude, such as listing available models.
 *
 * Claude API endpoint: GET /v1/models
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Claude\Endpoints
 * @since 1.0.9
 */
class Model_Endpoint extends Claude_Endpoint {

	/**
	 * Model_Endpoint constructor.
	 *
	 * @param  mixed  $utility  Utility object containing configuration and tools.
	 *
	 * @since 1.0.9
	 */
	public function __construct( $utility ) {
		parent::__construct( $utility );
	}

	/**
	 * Retrieve a specific model by ID.
	 *
	 * Claude API: GET /v1/models/{model_id}
	 *
	 * @param  AI_Model  $model  The model to retrieve.
	 *
	 * @return AI_Model The model details.
	 * @throws Exception If retrieval fails.
	 * @since 1.0.9
	 */
	public function retrieve( AI_Model $model ): AI_Model {
		$http_client = $this->http_client_factory();
		$response    = $http_client->get(
			self::API_BASE_URL . '/models/' . $model->get_name(),
			array(
				'headers' => $this->get_header(),
				'timeout' => $this->utility->get_timeout(),
			)
		);

		$handler = new Model_Response_Handler( $response, $http_client, $this );
		$body    = $handler->get_body();

		if ( ! empty( $body ) ) {
			// Update model with response data
			return $model;
		}

		throw new Exception( Error_Codes::NOT_FOUND, __( 'Model not found', 'limb-chatbot' ) );
	}

	/**
	 * List all available models for the Claude provider.
	 *
	 * Claude API: GET /v1/models
	 *
	 * @return array List of models.
	 * @throws Exception If API call fails.
	 * @since 1.0.9
	 */
	public function list() {
		$http_client = $this->http_client_factory();
		$response    = $http_client->get(
			self::API_BASE_URL . '/models',
			array(
				'headers' => $this->get_header(),
				'timeout' => $this->utility->get_timeout(),
			)
		);

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

	/**
	 * Delete a model.
	 *
	 * Note: Claude does not support model deletion via API.
	 *
	 * @throws Exception Always, because not supported.
	 * @since 1.0.9
	 */
	public function delete() {
		throw new Exception( Error_Codes::NOT_SUPPORTED,
			__( 'Claude does not support model deletion', 'limb-chatbot' ) );
	}
}

