<?php

namespace Limb_Chatbot\Includes\AI_Providers\Gemini\Services;


use Limb_Chatbot\Includes\Data_Objects\Message;
use Limb_Chatbot\Includes\Services\Helper;

/**
 * Class Message_Service
 *
 * Prepares messages for the Gemini AI provider by formatting the content
 * according to Gemini API requirements.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Gemini\Services
 * @since 1.0.0
 */
class Message_Service {

	/**
	 * Role constant representing assistant/model in Gemini.
	 */
	const GEMINI_ROLE_ASSISTANT = 'model';

	/**
	 * Role constant representing user in Gemini.
	 */
	const GEMINI_ROLE_USER = 'user';

	/**
	 * Prepares a message array to be sent to Gemini API.
	 *
	 * - Ignores system role messages.
	 * - Converts content parts into Gemini API expected format.
	 *
	 * @param  Message  $message  Message object to prepare.
	 *
	 * @return array|null Prepared message array or null if ignored.
	 * @since 1.0.0
	 */
	public function prepare_message( Message $message ) {
		if ( $message->get_role() == 'system' ) {
			return null;
		}
		$to_sent_parts = [];
		$content       = $message->get_content();
		foreach ( $content as $part ) {
			if ( $part['type'] === Message::CONTENT_TYPE_SLACK_CONNECTION ) {
				// Skip Slack connection parts
				continue;
			}
			if ( $part['type'] === 'text' ) {
				$to_sent_parts[] = [ 'text' => $part['text']['value'] ];
			} elseif ( $part['type'] === 'attachment' ) {
				$to_sent_parts[] = [
					'inline_data' => [
						'mime_type' => $part['attachment']['mime_type'],
						'data'      => preg_replace( '#^data:image/\w+;base64,#i',
							'',
							$part['attachment']['value'] )
					]
				];
			} elseif ( $part['type'] === Message::CONTENT_TYPE_ACTION_SUBMISSION ) {
				$to_sent_parts[] = [ 'text' => $part[ Message::CONTENT_TYPE_ACTION_SUBMISSION ]['message'] ];
			} elseif ( $part['type'] === Message::CONTENT_TYPE_ACTION_CANCELLATION ) {
				$text      = ! empty( $part[ Message::CONTENT_TYPE_ACTION_CANCELLATION ]['text'] ) ? $part[ Message::CONTENT_TYPE_ACTION_CANCELLATION ]['text'] : __( 'Cancel submission of this action', 'limb-chatbot' );
				$to_sent_parts[] = [ 'text' => $text ];
			} elseif ($part['type'] === Message::CONTENT_TYPE_LIVE_AGENT_DISCONNECTION){
				$text      = ! empty( $part[ Message::CONTENT_TYPE_LIVE_AGENT_DISCONNECTION ]['text'] ) ? $part[ Message::CONTENT_TYPE_LIVE_AGENT_DISCONNECTION ]['text'] : __( 'Disconnect from live agent', 'limb-chatbot' );
				$to_sent_parts[] = [ 'text' => $text ];
			}
		}

		return [
			'role'  => $message->role === Message::ROLE_USER ? self::GEMINI_ROLE_USER : self::GEMINI_ROLE_ASSISTANT,
			'parts' => $to_sent_parts,
		];
	}
}