<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Niwa_AI_Admin_Autonomy_Telegram_Reactions {

    /** @var Niwa_AI_Admin_Autonomy_Telegram|null */
    private $telegram;

    /** @var Niwa_AI_Admin_Autonomy_Store|null */
    private $conversation_store;

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

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

    public function handle( $message ) {
        $message = is_array( $message ) ? $message : array();
        if ( 'reaction' !== ( $message['kind'] ?? '' ) ) {
            return null;
        }

        $emojis = isset( $message['reaction_emojis'] ) ? (array) $message['reaction_emojis'] : array();
        $this->log(
            'message_reaction',
            array(
                'chat_id'    => isset( $message['chat_id'] ) ? (string) $message['chat_id'] : '',
                'from_id'    => isset( $message['from_id'] ) ? (string) $message['from_id'] : '',
                'message_id' => isset( $message['message_id'] ) ? intval( $message['message_id'] ) : 0,
                'emojis'     => $emojis,
            )
        );

        $cleaned_emojis = array();
        foreach ( $emojis as $emoji ) {
            $emoji = trim( (string) $emoji );
            if ( '' !== $emoji ) {
                $cleaned_emojis[] = $emoji;
            }
        }

        if ( ! empty( $cleaned_emojis ) && $this->conversation_store && method_exists( $this->conversation_store, 'append' ) ) {
            $session_id = '';
            if ( isset( $message['chat_id'] ) ) {
                $session_id = $this->get_founder_session_id( $message['chat_id'] );
            }

            if ( '' !== $session_id ) {
                $original_message_id = isset( $message['message_id'] ) ? intval( $message['message_id'] ) : 0;
                $synthetic_text      = '[Founder reacted ' . implode( ' ', $cleaned_emojis ) . ' to message #' . $original_message_id . ']';

                try {
                    $this->conversation_store->append( $session_id, 'user', $synthetic_text );
                } catch ( Throwable $e ) {
                    $this->log(
                        'message_reaction_append_failed',
                        array(
                            'session_id' => $session_id,
                            'error'      => $e->getMessage(),
                        )
                    );
                }
            }
        }

        if ( ! empty( $message['update_id'] ) && $this->telegram && method_exists( $this->telegram, 'remember_processed_update' ) ) {
            $this->telegram->remember_processed_update( $message['update_id'] );
        }

        return array(
            'success' => true,
            'ignored' => true,
        );
    }

    private function get_founder_session_id( $chat_id ) {
        return (string) $this->call( 'get_founder_session_id', '', array( $chat_id ) );
    }

    private function log( $event, $context = array() ) {
        $this->call( 'debug_logger', null, array( $event, $context ) );
    }

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