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

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

final class Replyan_AI_Gemini {

	/**
	 * Send a chat request to the Google Gemini 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() ) {
		$contents = array();

		// Build conversation history. Gemini uses 'user' and 'model' roles (not 'assistant').
		foreach ( $history as $msg ) {
			if ( isset( $msg['role'], $msg['content'] ) ) {
				$role = $msg['role'];
				if ( 'assistant' === $role ) {
					$role = 'model';
				}
				if ( in_array( $role, array( 'user', 'model' ), true ) ) {
					$contents[] = array(
						'role'  => $role,
						'parts' => array( array( 'text' => $msg['content'] ) ),
					);
				}
			}
		}

		// Append the current user message.
		$contents[] = array(
			'role'  => 'user',
			'parts' => array( array( 'text' => $message ) ),
		);

		// Combine adjacent messages with the same role to prevent API errors.
		$normalized = array();
		foreach ( $contents as $msg ) {
			$last_index = count( $normalized ) - 1;
			if ( $last_index >= 0 && $normalized[ $last_index ]['role'] === $msg['role'] ) {
				$normalized[ $last_index ]['parts'][] = $msg['parts'][0];
			} else {
				$normalized[] = $msg;
			}
		}

		// Gemini requires the first message to be from 'user'.
		if ( ! empty( $normalized ) && 'model' === $normalized[0]['role'] ) {
			array_unshift( $normalized, array(
				'role'  => 'user',
				'parts' => array( array( 'text' => '(Continued conversation)' ) ),
			) );
		}

		$body_args = array(
			'contents'         => $normalized,
			'generationConfig' => array(
				'maxOutputTokens' => absint( $settings['max_tokens'] ),
				'temperature'     => (float) $settings['temperature'],
			),
		);

		// Add system instruction if available.
		if ( ! empty( $settings['system_prompt'] ) ) {
			$body_args['systemInstruction'] = array(
				'parts' => array( array( 'text' => $settings['system_prompt'] ) ),
			);
		}

		$api_key = ! empty( $settings['gemini_api_key'] ) ? $settings['gemini_api_key'] : $settings['api_key'];
		$model   = $settings['model'];

		$url = sprintf(
			'%s/models/%s:generateContent?key=%s',
			Replyan_AI_Endpoints::GEMINI_BASE,
			rawurlencode( $model ),
			rawurlencode( $api_key )
		);

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