<?php

namespace Limb_Chatbot\Includes\AI_Providers\Gemini\Services;


use Limb_Chatbot\Includes\Data_Objects\Message;

/**
 * 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.
	 * - Applies filters for WooCommerce and live-agent content types.
	 *
	 * @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();
		$has_wc_context_text = false;

		foreach ( $content as $part ) {
			$part_type = $part['type'] ?? '';

			if (
				$part_type === Message::CONTENT_TYPE_PARAMETER
				|| $part_type === Message::CONTENT_TYPE_PARAMETER_VALUE
			) {
				$filtered_text = apply_filters(
					"limb_chatbot_message_content_part_{$part_type}",
					$part['text']['value'] ?? '',
					$part
				);
				$filtered_text = is_string( $filtered_text ) ? trim( $filtered_text ) : '';

				if ( '' === $filtered_text ) {
					continue;
				}

				$to_sent_parts[]     = [ 'text' => $filtered_text, '__wc_context' => true ];
				$has_wc_context_text = true;
				continue;
			}

			if ( $part_type === 'text' ) {
				$to_sent_parts[] = [ 'text' => $part['text']['value'] ];
			} elseif ( $part_type === 'attachment' ) {
				continue;
			} 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 ];
			}
		}

		if ( $has_wc_context_text ) {
			$to_sent_parts = array_values( array_filter( $to_sent_parts, static function ( $part ) {
				return ! empty( $part['__wc_context'] );
			} ) );
		}

		foreach ( $to_sent_parts as &$part ) {
			unset( $part['__wc_context'] );
		}
		unset( $part );

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