<?php
/**
 * OpenRouter implementation for Replyan AI.
 *
 * @package Replyan_AI
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Replyan_AI_OpenRouter {

	/**
	 * Send a chat request to the OpenRouter API.
	 *
	 * @param array  $settings Plugin settings (API key, model, etc.)
	 * @param string $message  The user message
	 * @param array  $history  Chat history array
	 * @return array|\WP_Error The HTTP response
	 */
	public static function send_request( array $settings, string $message, array $history = array() ) {
		$messages = array_merge(
			array(
				array(
					'role'    => 'system',
					'content' => $settings['system_prompt'],
				),
			),
			$history,
			array(
				array(
					'role'    => 'user',
					'content' => $message,
				),
			)
		);

		$body_args = array(
			'model'       => $settings['model'],
			'messages'    => $messages,
			'max_tokens'  => absint( $settings['max_tokens'] ),
			'temperature' => (float) $settings['temperature'],
		);

		return wp_remote_post(
			Replyan_AI_Endpoints::OPENROUTER_CHAT_COMPLETIONS,
			array(
				'timeout' => isset( $settings['timeout'] ) ? absint( $settings['timeout'] ) : 60,
				'headers' => array(
					'Authorization' => 'Bearer ' . $settings['openrouter_api_key'],
					'Content-Type'  => 'application/json',
					'HTTP-Referer'  => site_url(),
					'X-Title'       => get_bloginfo( 'name' ),
				),
				'body'    => wp_json_encode( $body_args ),
			)
		);
	}
}
