<?php
/**
 * OpenRouter API client.
 *
 * @package OpenRouterSiteChatbotByJayanta
 */

defined( 'ABSPATH' ) || exit;

/**
 * Server-side wrapper for OpenRouter Chat Completions.
 */
class ORSC_OpenRouter_Client {
	/**
	 * API key.
	 *
	 * @var string
	 */
	private $api_key;

	/**
	 * Model.
	 *
	 * @var string
	 */
	private $model;

	/**
	 * Max tokens.
	 *
	 * @var int
	 */
	private $max_tokens;

	/**
	 * Temperature.
	 *
	 * @var float
	 */
	private $temperature;

	/**
	 * Constructor.
	 *
	 * @param string $api_key API key.
	 * @param string $model Model name.
	 * @param int    $max_tokens Max response tokens.
	 * @param float  $temperature Sampling temperature.
	 */
	public function __construct( $api_key, $model, $max_tokens, $temperature ) {
		$this->api_key     = trim( (string) $api_key );
		$this->model       = trim( (string) $model );
		$this->max_tokens  = absint( $max_tokens );
		$this->temperature = (float) $temperature;
	}

	/**
	 * Ask OpenRouter.
	 *
	 * @param string $system_prompt System prompt.
	 * @param array  $messages Conversation messages.
	 * @return array|WP_Error
	 */
	public function chat( $system_prompt, $messages ) {
		if ( '' === $this->api_key ) {
			return new WP_Error( 'orsc_missing_api_key', __( 'The chatbot is not configured yet. Please add an OpenRouter API key.', 'jayanta-ai-site-chatbot-with-openrouter' ), array( 'status' => 400 ) );
		}

		$payload_messages = array_merge(
			array(
				array(
					'role'    => 'system',
					'content' => $system_prompt,
				),
			),
			$messages
		);

		$response = wp_remote_post(
			'https://openrouter.ai/api/v1/chat/completions',
			array(
				'timeout' => 45,
				'headers' => array(
					'Authorization' => 'Bearer ' . $this->api_key,
					'Content-Type'  => 'application/json',
					'HTTP-Referer'  => home_url( '/' ),
					'X-Title'       => get_bloginfo( 'name' ),
				),
				'body'    => wp_json_encode(
					array(
						'model'       => $this->model ? $this->model : 'openai/gpt-4o-mini',
						'messages'    => $payload_messages,
						'temperature' => $this->temperature,
						'max_tokens'  => $this->max_tokens ? $this->max_tokens : 600,
					)
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$status = wp_remote_retrieve_response_code( $response );
		$data   = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( 200 > $status || 299 < $status ) {
			$message = isset( $data['error']['message'] ) ? $data['error']['message'] : __( 'OpenRouter returned an error.', 'jayanta-ai-site-chatbot-with-openrouter' );
			return new WP_Error( 'orsc_openrouter_error', sanitize_text_field( $message ), array( 'status' => $status ) );
		}

		$text = isset( $data['choices'][0]['message']['content'] ) ? trim( (string) $data['choices'][0]['message']['content'] ) : '';

		if ( '' === $text ) {
			return new WP_Error( 'orsc_empty_response', __( 'OpenRouter returned an empty response.', 'jayanta-ai-site-chatbot-with-openrouter' ), array( 'status' => 502 ) );
		}

		return array(
			'answer' => $text,
			'usage'  => isset( $data['usage'] ) && is_array( $data['usage'] ) ? $data['usage'] : array(),
		);
	}
}

