<?php
/**
 * Handles Telegram message gates before actor enqueue.
 */

defined( 'ABSPATH' ) || exit;

class Niwa_AI_Admin_Autonomy_Telegram_Message_Gates {

    private $telegram;
    private $callbacks;

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

    public function before_actor_intake( $message ) {
        $message   = is_array( $message ) ? $message : 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;

        $is_combined_payload = ! empty( $message['is_album'] ) || ! empty( $message['is_text_fragment'] );
        if ( ! $is_combined_payload && $update_id > 0 ) {
            $reserved = method_exists( $this->telegram, 'reserve_processed_update' )
                ? $this->telegram->reserve_processed_update( $update_id )
                : ! $this->telegram->is_duplicate_update( $update_id );

            if ( ! $reserved ) {
                $this->log_message_event( 'incoming_message_duplicate', $message );
                return $this->handled( array(
                    'success' => true,
                    'ignored' => true,
                ) );
            }
        }

        $text = isset( $message['text'] ) ? (string) $message['text'] : '';
        if ( $this->call( 'is_stop_command_text', array( $text ), false ) ) {
            $session_id = (string) $this->call( 'resolve_actor_session_id', array( $message ), '' );
            $reply      = (string) $this->call(
                'stop_runtime_for_session',
                array( $session_id, $chat_id, $message_id, 'telegram' ),
                ''
            );

            if ( '' !== $chat_id ) {
                $this->telegram->send_message( $chat_id, $reply, $message_id );
            }
            $this->call(
                'remember_exchange',
                array(
                    $chat_id,
                    $text,
                    $reply,
                    array(
                        'session_id' => $session_id,
                        'channel'    => isset( $message['channel'] ) ? sanitize_key( (string) $message['channel'] ) : 'telegram',
                        'message_id' => $message_id,
                    ),
                ),
                null
            );
            $this->remember_processed_update( $update_id );

            return $this->handled( array(
                'success' => true,
                'reply'   => $reply,
                'stopped' => true,
            ) );
        }

        $rate = $this->telegram->consume_rate_limit( $chat_id );
        if ( empty( $rate['allowed'] ) ) {
            $this->log_message_event( 'incoming_message_rate_limited', $message );
            $reply = 'Rate limit aktiviran. Sacekaj minut pa posalji sledecu poruku.';
            $this->telegram->send_message( $chat_id, $reply, $message_id );
            if ( ! empty( $message['callback_query_id'] ) ) {
                $this->telegram->answer_callback_query( $message['callback_query_id'], $reply );
            }
            $this->call(
                'remember_exchange',
                array(
                    $chat_id,
                    $text,
                    $reply,
                    array(
                        'session_id' => (string) $this->call( 'resolve_actor_session_id', array( $message ), '' ),
                        'channel'    => isset( $message['channel'] ) ? sanitize_key( (string) $message['channel'] ) : 'telegram',
                        'message_id' => $message_id,
                    ),
                ),
                null
            );
            $this->remember_processed_update( $update_id );

            return $this->handled( array(
                'success' => true,
                'reply'   => $reply,
            ) );
        }

        $callback_acknowledged = false;
        if ( ! empty( $message['callback_query_id'] ) ) {
            $this->telegram->answer_callback_query( $message['callback_query_id'] );
            $callback_acknowledged = true;
        }

        return array(
            'handled'               => false,
            'callback_acknowledged' => $callback_acknowledged,
        );
    }

    private function handled( $result ) {
        return array(
            'handled' => true,
            'result'  => is_array( $result ) ? $result : array(
                'success' => true,
                'ignored' => true,
            ),
        );
    }

    private function remember_processed_update( $update_id ) {
        $update_id = intval( $update_id );
        if ( $update_id > 0 ) {
            $this->telegram->remember_processed_update( $update_id );
        }
    }

    private function log_message_event( $event, $message ) {
        $this->call(
            'debug_logger',
            array(
                $event,
                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,
                ),
            ),
            null
        );
    }

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