<?php
/**
 * AI Assistant Plugin
 * Provides AI-powered responses using Gemini
 */

declare(strict_types=1);

class AIAssistantPlugin extends BasePlugin {
    protected string $name = 'AIAssistant';
    protected string $version = '1.0.0';
    protected string $description = 'AI-powered assistant using Gemini';
    protected string $author = 'Kiro AI';
    private ?GeminiAI $ai = null;
    
    public function onEnable(): void {
        $this->ai = GeminiAI::getInstance();
        $this->log('AI Assistant Plugin enabled');
    }
    
    public function onDisable(): void {
        $this->log('AI Assistant Plugin disabled');
    }
    
    /**
     * Called when message is received
     */
    public function onMessage(array $data): void {
        $chatId = $data['chat_id'] ?? null;
        $userId = $data['user_id'] ?? null;
        $text = $data['text'] ?? '';
        $chatType = $data['chat_type'] ?? 'private';
        
        if (!$chatId || !$text) {
            return;
        }
        
        // Check if message is for AI
        $config = $this->getConfig();
        $trigger = $config['trigger'] ?? 'ai';
        
        // In groups, only respond if mentioned or triggered
        if ($chatType !== 'private') {
            if (stripos($text, $trigger) !== 0 && stripos($text, '@' . BOT_USERNAME) === false) {
                return;
            }
            
            // Remove trigger from text
            $text = preg_replace('/^' . preg_quote($trigger, '/') . '\s*/i', '', $text);
            $text = str_replace('@' . BOT_USERNAME, '', $text);
        }
        
        // Send "thinking" message
        $thinkingMsg = $this->telegram->sendMessage(
            $chatId,
            __('ai.thinking')
        );
        
        // Get AI response
        $response = $this->ai->chat($text, $userId);
        
        // Delete thinking message
        if ($thinkingMsg && isset($thinkingMsg->result->message_id)) {
            $this->telegram->deleteMessage($chatId, $thinkingMsg->result->message_id);
        }
        
        // Send AI response
        if ($response) {
            $this->telegram->sendMessage($chatId, $response);
            $this->log("AI response sent to user {$userId}");
        }
    }
    
    /**
     * Called when command is received
     */
    public function onCommand(array $data): void {
        $command = $data['command'] ?? '';
        $chatId = $data['chat_id'] ?? null;
        $userId = $data['user_id'] ?? null;
        
        if (!$chatId) {
            return;
        }
        
        switch ($command) {
            case 'ai':
            case 'هوش_مصنوعی':
                $this->showAIMenu($chatId);
                break;
                
            case 'clearai':
            case 'پاک_کردن_تاریخچه':
                $this->ai->clearHistory($userId);
                $this->telegram->sendMessage(
                    $chatId,
                    "✅ تاریخچه گفتگو با هوش مصنوعی پاک شد!"
                );
                break;
        }
    }
    
    /**
     * Show AI menu
     */
    private function showAIMenu(int $chatId): void {
        $keyboard = [
            'inline_keyboard' => [
                [
                    ['text' => '💬 چت با AI', 'callback_data' => 'ai_chat'],
                    ['text' => '🔍 تحلیل احساسات', 'callback_data' => 'ai_sentiment']
                ],
                [
                    ['text' => '📝 خلاصه‌سازی', 'callback_data' => 'ai_summarize'],
                    ['text' => '🌐 ترجمه', 'callback_data' => 'ai_translate']
                ],
                [
                    ['text' => '🗑 پاک کردن تاریخچه', 'callback_data' => 'ai_clear']
                ]
            ]
        ];
        
        $this->telegram->sendMessage(
            $chatId,
            "🤖 *منوی هوش مصنوعی*\n\nلطفاً یکی از گزینه‌ها را انتخاب کنید:",
            'Markdown',
            $keyboard
        );
    }
    
    private function log(string $message): void {
        $logFile = LOGS_PATH . '/plugins_' . date('Y-m-d') . '.log';
        $timestamp = date('Y-m-d H:i:s');
        file_put_contents($logFile, "[{$timestamp}] [AIAssistant] {$message}\n", FILE_APPEND);
    }
}
