<?php

namespace Limb_Chatbot\Includes\Integrations\Telegram\Services;

use Limb_Chatbot\Includes\Data_Objects\Chat;
use Limb_Chatbot\Includes\Data_Objects\Chatbot_User;
use Limb_Chatbot\Includes\Data_Objects\Message;

/**
 * Telegram Bot Message Builder
 *
 * Builds formatted HTML messages for Telegram bot communications.
 * Provides consistent message formatting across the Telegram integration.
 *
 * @package Limb_Chatbot\Includes\Integrations\Telegram\Services
 * @since 1.0.11
 */
class Telegram_Bot_Message_Builder {

	/**
	 * Divider line for message sections.
	 */
	const DIVIDER = "━━━━━━━━━━━━━━━━━━━━━━";

	/**
	 * Build new support request notification message.
	 *
	 * @param string $topic_name Topic name.
	 *
	 * @return string Formatted HTML message.
	 * @since 1.0.11
	 */
	public function build_new_topic_notification( string $topic_name ): string {
		return sprintf(
			"🔔 <b>New Request</b>\n\n" .
			"A new topic has been created:\n" .
			"📋 <b>Topic:</b> %s\n\n" .
			"Please check the topic",
			esc_html( $topic_name )
		);
	}


	/**
	 * Build initial live agent request message.
	 *
	 * @param Chat   $chat   Chat instance.
	 * @param string $reason Connection reason.
	 *
	 * @return string Formatted HTML message.
	 * @since 1.0.11
	 */
	public function build_initial_message( Chat $chat, string $reason = '' ): string {
		$participant = $chat->get_user_participant();
		$user_name   = $participant instanceof Chatbot_User ? $participant->name() : 'Guest User';
		$user_email  = $participant instanceof Chatbot_User ? $participant->email() : 'N/A';
		$user_ip     = $participant instanceof Chatbot_User ? $participant->get_ip() : 'N/A';
		$chat_id     = $chat->get_uuid();
		$timestamp   = $this->get_formatted_timestamp();

		return "🔔 <b>New Live Agent Request</b>\n\n" .
		       self::DIVIDER . "\n\n" .
		       "👤 <b>Customer:</b> " . esc_html( $user_name ) . "\n" .
		       "📧 <b>Email:</b> " . esc_html( $user_email ) . "\n" .
		       "🌐 <b>IP Address:</b> " . esc_html( $user_ip ) . "\n" .
		       "🆔 <b>Chat ID:</b> <code>" . esc_html( $chat_id ) . "</code>\n\n" .
		       self::DIVIDER . "\n\n" .
		       "💬 <b>Reason:</b>\n" . esc_html( $reason ?: 'Customer requested human assistance' ) . "\n\n" .
		       self::DIVIDER . "\n\n" .
		       "🕐 " . esc_html( $timestamp ) . "\n\n" .
		       "💡 <i>Type #close, #end, or #done to close this session</i>";
	}

	/**
	 * Build conversation history message.
	 *
	 * @param array $messages Array of Message objects.
	 * @param int   $max_text_length Maximum text length per message.
	 *
	 * @return string Formatted HTML message.
	 * @since 1.0.11
	 */
	public function build_history_message( array $messages, int $max_text_length = 500 ): string {
		$history_text = "📚 <b>Conversation History</b>\n\n" .
		                self::DIVIDER . "\n\n";

		foreach ( $messages as $message ) {
			if ( ! $message instanceof Message ) {
				continue;
			}

			$role       = $message->get_role();
			$role_icon  = $role === 'user' ? '👤' : '🤖';
			$role_label = $role === 'user' ? 'Customer' : 'AI Assistant';
			$content    = $this->truncate_text( $message->extract_text(), $max_text_length );
			$timestamp  = $message->get_created_at();
			$time_str   = $timestamp ? date( 'g:i A', strtotime( $timestamp ) ) : '';

			$history_text .= sprintf(
				"<b>%s %s</b> <i>(%s)</i>\n%s\n\n",
				$role_icon,
				esc_html( $role_label ),
				esc_html( $time_str ),
				esc_html( $content )
			);
		}

		return $history_text;
	}

	/**
	 * Build chat message for forwarding to Telegram.
	 *
	 * @param Message $message      Message instance.
	 * @param int     $max_length   Maximum content length.
	 *
	 * @return string Formatted HTML message.
	 * @since 1.0.11
	 */
	public function build_chat_message( Message $message, int $max_length = 3000 ): string {
		$role       = $message->get_role();
		$role_icon  = $role === 'user' ? '👤' : '🤖';
		$role_label = $role === 'user' ? 'Customer' : 'AI Assistant';
		$content    = $this->truncate_text( $message->extract_text(), $max_length );

		return sprintf(
			"<b>%s %s</b>\n\n%s",
			$role_icon,
			esc_html( $role_label ),
			esc_html( $content )
		);
	}

	/**
	 * Build session ended message.
	 *
	 * @param Chat $chat Chat instance.
	 *
	 * @return string Formatted HTML message.
	 * @since 1.0.11
	 */
	public function build_session_ended_message( Chat $chat ): string {
		$participant = $chat->get_user_participant();
		$user_name   = $participant instanceof Chatbot_User ? $participant->name() : 'Guest User';
		$timestamp   = $this->get_formatted_timestamp();

		return "👋 <b>Live Agent Session Ended</b>\n\n" .
		       self::DIVIDER . "\n\n" .
		       "👤 <b>Customer:</b> " . esc_html( $user_name ) . "\n" .
		       "🆔 <b>Chat ID:</b> <code>" . esc_html( $chat->get_uuid() ) . "</code>\n\n" .
		       "✅ <b>Session Concluded</b>\n" .
		       "Thank you for your assistance!\n\n" .
		       self::DIVIDER . "\n\n" .
		       "🕐 " . esc_html( $timestamp );
	}

	/**
	 * Get formatted timestamp.
	 *
	 * @return string Formatted timestamp.
	 * @since 1.0.11
	 */
	private function get_formatted_timestamp(): string {
		return date( 'F j, Y \a\t g:i A' );
	}

	/**
	 * Truncate text to specified length.
	 *
	 * @param string $text   Text to truncate.
	 * @param int    $length Maximum length.
	 *
	 * @return string Truncated text.
	 * @since 1.0.11
	 */
	private function truncate_text( string $text, int $length = 500 ): string {
		if ( strlen( $text ) <= $length ) {
			return $text;
		}

		return substr( $text, 0, $length ) . '...';
	}
}

