<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints;

use Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints\Response\Handlers\Response_Response_Handler;
use Limb_Chatbot\Includes\Data_Objects\File;
use Limb_Chatbot\Includes\Data_Objects\Message;
use Limb_Chatbot\Includes\Services\Collection;

/**
 * Class Response_Endpoint
 *
 * Handles OpenRouter Response API interactions.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints
 * @since 1.0.14
 */
class Response_Endpoint extends Open_Router_Endpoint {

	/**
	 * Constructor.
	 *
	 * @param mixed $utility Utility object.
	 */
	public function __construct( $utility ) {
		parent::__construct( $utility );
	}

	/**
	 * Generate a response using the OpenRouter Responses API.
	 *
	 * @param array $params Custom parameters for the request body.
	 *
	 * @return Response_Response_Handler
	 */
	public function generate( array $params = [] ) {
		$http_client = $this->http_client_factory();
		$model       = $this->utility->global_utility->get_ai_model();

		$body = array_merge( [
			'model' => $model->get_name(),
		], $params );

		$response = $http_client->post( self::API_BASE_URL . '/responses', array(
			'headers' => $this->get_header(),
			'body'    => json_encode( $body ),
			'timeout' => $this->utility->get_timeout() ?? 300,
		) );

		return new Response_Response_Handler( $response, $http_client, $this );
	}

	/**
	 * Generate a response from a file context.
	 *
	 * @param Message $system_message
	 * @param File $file
	 * @return Collection
	 */
	public function generate_from_file( Message $system_message, File $file ) {
		$model = $this->utility->global_utility->get_ai_model();

		$input = [];
		if ( ! empty( $system_message->extract_text() ) ) {
			$input[] = [
				'role' => 'system',
				'content' => $system_message->extract_text()
			];
		}

		$input[] = [
			'role' => 'user',
			'content' => [
				[
					'type' => 'input_file',
					'file_url' => $file->url,
				],
			],
		];

		$body = [
			'model'        => $model->get_name(),
			'input'        => $input,
			'temperature'  => 0.3,
			'top_p'        => 0.9,
		];

		$http_client = $this->http_client_factory();
		$response    = $http_client->post( self::API_BASE_URL . '/responses', array(
			'headers' => $this->get_header(),
			'body'    => json_encode( $body ),
			'timeout' => 300,
		) );

		return ( new Response_Response_Handler( $response, $http_client, $this ) )->get_dataset_entries();
	}
}
