<?php
/**
 * Formats Telegram buffer transport debug events.
 *
 * @package Niwa_AI
 */

defined( 'ABSPATH' ) || exit;

class Niwa_AI_Admin_Autonomy_Telegram_Buffer_Event_Logger {
	/** @var array<string,callable> */
	private $callbacks;

	public function __construct( $callbacks = array() ) {
		$this->callbacks = is_array( $callbacks ) ? $callbacks : array();
	}

	public function log( $event, $message, $extra = array() ) {
		$event   = sanitize_key( (string) $event );
		$message = is_array( $message ) ? $message : array();
		if ( '' === $event || empty( $message ) ) {
			return;
		}

		$text = '';
		if ( isset( $message['text_only'] ) ) {
			$text = (string) $message['text_only'];
		} elseif ( isset( $message['text'] ) ) {
			$text = (string) $message['text'];
		} elseif ( isset( $message['caption'] ) ) {
			$text = (string) $message['caption'];
		}

		$payload = array(
			'chat_id'              => isset( $message['chat_id'] ) ? (string) $message['chat_id'] : '',
			'message_id'           => isset( $message['message_id'] ) ? intval( $message['message_id'] ) : 0,
			'update_id'            => isset( $message['update_id'] ) ? intval( $message['update_id'] ) : 0,
			'kind'                 => isset( $message['kind'] ) ? (string) $message['kind'] : '',
			'text_length'          => $this->call( 'text_length', array( $text ), strlen( $text ) ),
			'text_preview'         => $this->call( 'text_substr', array( $text, 0, 500 ), substr( $text, 0, 500 ) ),
			'is_text_fragment'     => ! empty( $message['is_text_fragment'] ),
			'fragment_count'       => intval( isset( $message['fragment_count'] ) ? $message['fragment_count'] : 0 ),
			'fragment_message_ids' => isset( $message['fragment_message_ids'] ) && is_array( $message['fragment_message_ids'] )
				? array_values( array_map( 'intval', $message['fragment_message_ids'] ) )
				: array(),
			'is_album'             => ! empty( $message['is_album'] ),
			'album_size'           => intval( isset( $message['album_size'] ) ? $message['album_size'] : 0 ),
			'album_message_ids'    => isset( $message['album_message_ids'] ) && is_array( $message['album_message_ids'] )
				? array_values( array_map( 'intval', $message['album_message_ids'] ) )
				: array(),
			'text_buffer_ttl'      => class_exists( 'Niwa_AI_Admin_Autonomy_Telegram_Album_Buffer' )
				? Niwa_AI_Admin_Autonomy_Telegram_Album_Buffer::TEXT_FRAG_TTL_SECONDS
				: 0,
		);

		if ( ! empty( $extra ) && is_array( $extra ) ) {
			$payload = array_merge( $payload, $extra );
		}

		$this->call( 'debug_logger', array( $event, $payload ) );
	}

	private function call( $name, $args = array(), $default = null ) {
		return Niwa_AI_Admin_Autonomy_Callbacks::call( $this->callbacks, $name, $args, $default );
	}
}
