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

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

final class Replyan_AI_OpenAI {

	/**
	 * Send a chat request to the OpenAI 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,
		);

		$is_strict_model = strpos( $settings['model'], 'o1' ) === 0 || strpos( $settings['model'], 'o3' ) === 0 || strpos( $settings['model'], 'gpt-5' ) === 0 || strpos( $settings['model'], 'chatgpt-5' ) === 0;

		// Newer OpenAI models use max_completion_tokens and enforce default temperature
		if ( $is_strict_model ) {
			$body_args['max_completion_tokens'] = absint( $settings['max_tokens'] );
			$body_args['temperature'] = 1;
		} else {
			$body_args['max_tokens']  = absint( $settings['max_tokens'] );
			$body_args['temperature'] = (float) $settings['temperature'];
		}

		return wp_remote_post(
			Replyan_AI_Endpoints::OPENAI_CHAT_COMPLETIONS,
			array(
				'timeout' => isset( $settings['timeout'] ) ? absint( $settings['timeout'] ) : 60,
				'headers' => array(
					'Authorization' => 'Bearer ' . $settings['api_key'],
					'Content-Type'  => 'application/json',
				),
				'body'    => wp_json_encode( $body_args ),
			)
		);
	}
}
