<?php
namespace Limb_Chatbot\Includes\Services;

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

class Conversation_Formatter{
	public function format_chat_conversation(Chat $chat, $limit = 10){
		if ( ! $chat ) {
			return '[no conversation history]';
		}

		$limit    = max( 1, (int) $limit );
		$messages = $chat->get_messages( $limit );
		if ( ! is_array( $messages ) || empty( $messages ) ) {
			return '[no conversation history]';
		}

		// `get_messages()` returns newest-first; reverse to keep a natural oldest-to-newest reading order.
		$messages = array_reverse( $messages );
		$lines    = [];
		foreach ( $messages as $message ) {
			if ( ! $message instanceof Message ) {
				continue;
			}
			$text    = '';
			$content = $message->get_content();
			foreach ( $content ?? [] as $part ) {
				if (
					is_array( $part )
					&& isset( $part['type'] )
					&& 'wc_products' === $part['type']
				) {
					$text = is_string( $part['message_text'] ?? null ) ? trim( $part['message_text'] ) : '';
					break;
				}
			}
			if ( '' === $text ) {
				$text = trim( $message->extract_text() );
			}

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

			$role    = Message::ROLE_USER === $message->get_role() ? 'User' : 'Assistant';
			$lines[] = $role . ': ' . $this->normalize_context_line( $text );
		}

		return ! empty( $lines ) ? implode( "\n", $lines ) : '[no conversation history]';
	}



	private function normalize_context_line( string $text ): string {
		$single_line = preg_replace( '/\s+/', ' ', $text );
		if ( ! is_string( $single_line ) ) {
			return '';
		}

		return substr( trim( $single_line ), 0, 280 );
	}

}
