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

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

final class Replyan_AI_Anthropic {

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

		// Anthropic strictly requires 'user' and 'assistant' roles, and they must alternate.
		// For MVP, we pass them directly, but we skip any 'system' roles in history.
		foreach ( $history as $msg ) {
			if ( isset( $msg['role'], $msg['content'] ) ) {
				$role = $msg['role'];
				if ( in_array( $role, array( 'user', 'assistant' ), true ) ) {
					$anthropic_messages[] = array(
						'role'    => $role,
						'content' => $msg['content'],
					);
				}
			}
		}

		$anthropic_messages[] = array(
			'role'    => 'user',
			'content' => $message,
		);

		// Combine adjacent messages with the same role to prevent API errors.
		$normalized_messages = array();
		foreach ( $anthropic_messages as $msg ) {
			$last_index = count( $normalized_messages ) - 1;
			if ( $last_index >= 0 && $normalized_messages[ $last_index ]['role'] === $msg['role'] ) {
				$normalized_messages[ $last_index ]['content'] .= "\n\n" . $msg['content'];
			} else {
				$normalized_messages[] = $msg;
			}
		}
		
		// If the first message is assistant, prepend a dummy user message, since Anthropic requires starting with user.
		if ( ! empty( $normalized_messages ) && 'assistant' === $normalized_messages[0]['role'] ) {
			array_unshift( $normalized_messages, array( 'role' => 'user', 'content' => '(Continued conversation)' ) );
		}

		$body_args = array(
			'model'      => $settings['model'],
			'system'     => $settings['system_prompt'],
			'messages'   => $normalized_messages,
			'max_tokens' => absint( $settings['max_tokens'] ),
		);

		// Anthropic uses a 0.0 to 1.0 temperature scale (OpenAI is 0.0 to 2.0). 
		// We'll pass it as is, but cap it at 1.0 just in case.
		$body_args['temperature'] = (float) min( 1.0, max( 0.0, (float) $settings['temperature'] ) );

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

		return wp_remote_post(
			Replyan_AI_Endpoints::ANTHROPIC_MESSAGES,
			array(
				'timeout' => isset( $settings['timeout'] ) ? absint( $settings['timeout'] ) : 60,
				'headers' => array(
					'x-api-key'         => $api_key,
					'anthropic-version' => '2023-06-01',
					'Content-Type'      => 'application/json',
				),
				'body'    => wp_json_encode( $body_args ),
			)
		);
	}
}
