<?php
/**
 * Gemini AI Service
 * Version: 2.0
 * PHP: 7.4+
 */

declare(strict_types=1);

class GeminiAI {
    private static ?GeminiAI $instance = null;
    private string $apiKey;
    private string $apiUrl = 'https://generativelanguage.googleapis.com/v1beta/models/';
    private string $model = 'gemini-pro';
    private array $conversationHistory = [];
    private int $maxHistoryLength = 10;
    
    private function __construct() {
        $this->apiKey = defined('GEMINI_API_KEY') ? GEMINI_API_KEY : '';
    }
    
    public static function getInstance(): GeminiAI {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Chat with Gemini AI
     */
    public function chat(string $message, ?int $userId = null): ?string {
        if (empty($this->apiKey)) {
            return __('ai.no_api_key');
        }
        
        try {
            // Load conversation history for user
            if ($userId) {
                $this->loadConversationHistory($userId);
            }
            
            // Add user message to history
            $this->addToHistory('user', $message);
            
            // Prepare request
            $data = [
                'contents' => $this->formatHistory(),
                'generationConfig' => [
                    'temperature' => 0.7,
                    'topK' => 40,
                    'topP' => 0.95,
                    'maxOutputTokens' => 1024,
                ]
            ];
            
            $response = $this->makeRequest('generateContent', $data);
            
            if (!$response || !isset($response->candidates[0]->content->parts[0]->text)) {
                return __('ai.error');
            }
            
            $aiResponse = $response->candidates[0]->content->parts[0]->text;
            
            // Add AI response to history
            $this->addToHistory('model', $aiResponse);
            
            // Save conversation history
            if ($userId) {
                $this->saveConversationHistory($userId);
            }
            
            return $aiResponse;
            
        } catch (Exception $e) {
            $this->logError('Gemini AI Error: ' . $e->getMessage());
            return __('ai.error');
        }
    }
    
    /**
     * Analyze sentiment of text
     */
    public function analyzeSentiment(string $text): array {
        $prompt = "Analyze the sentiment of this text and respond with only one word: positive, negative, or neutral.\n\nText: {$text}";
        
        $response = $this->chat($prompt);
        $sentiment = strtolower(trim($response ?? 'neutral'));
        
        return [
            'sentiment' => $sentiment,
            'emoji' => $this->getSentimentEmoji($sentiment)
        ];
    }
    
    /**
     * Detect spam
     */
    public function detectSpam(string $text): bool {
        $prompt = "Is this message spam? Answer only 'yes' or 'no'.\n\nMessage: {$text}";
        
        $response = $this->chat($prompt);
        return stripos($response ?? '', 'yes') !== false;
    }
    
    /**
     * Summarize text
     */
    public function summarize(string $text, int $maxLength = 100): ?string {
        $prompt = "Summarize this text in maximum {$maxLength} characters:\n\n{$text}";
        return $this->chat($prompt);
    }
    
    /**
     * Translate text
     */
    public function translate(string $text, string $targetLang = 'en'): ?string {
        $langNames = [
            'en' => 'English',
            'fa' => 'Persian (Farsi)',
            'ar' => 'Arabic',
            'tr' => 'Turkish'
        ];
        
        $targetLanguage = $langNames[$targetLang] ?? 'English';
        $prompt = "Translate this text to {$targetLanguage}. Only provide the translation, nothing else:\n\n{$text}";
        
        return $this->chat($prompt);
    }
    
    /**
     * Answer question
     */
    public function answer(string $question): ?string {
        return $this->chat($question);
    }
    
    /**
     * Generate creative content
     */
    public function generate(string $prompt): ?string {
        return $this->chat($prompt);
    }
    
    /**
     * Make API request
     */
    private function makeRequest(string $endpoint, array $data): ?object {
        $url = $this->apiUrl . $this->model . ':' . $endpoint . '?key=' . $this->apiKey;
        
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json'
            ],
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CONNECTTIMEOUT => 10
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode !== 200 || !$response) {
            throw new Exception("API request failed with code: {$httpCode}");
        }
        
        return json_decode($response);
    }
    
    /**
     * Add message to conversation history
     */
    private function addToHistory(string $role, string $content): void {
        $this->conversationHistory[] = [
            'role' => $role,
            'parts' => [['text' => $content]]
        ];
        
        // Keep only last N messages
        if (count($this->conversationHistory) > $this->maxHistoryLength) {
            $this->conversationHistory = array_slice(
                $this->conversationHistory,
                -$this->maxHistoryLength
            );
        }
    }
    
    /**
     * Format history for API
     */
    private function formatHistory(): array {
        return $this->conversationHistory;
    }
    
    /**
     * Load conversation history from cache
     */
    private function loadConversationHistory(int $userId): void {
        $cacheFile = CACHE_PATH . "/ai_conversation_{$userId}.json";
        
        if (file_exists($cacheFile)) {
            $data = file_get_contents($cacheFile);
            $this->conversationHistory = json_decode($data, true) ?? [];
        }
    }
    
    /**
     * Save conversation history to cache
     */
    private function saveConversationHistory(int $userId): void {
        $cacheFile = CACHE_PATH . "/ai_conversation_{$userId}.json";
        file_put_contents($cacheFile, json_encode($this->conversationHistory));
    }
    
    /**
     * Clear conversation history
     */
    public function clearHistory(?int $userId = null): void {
        $this->conversationHistory = [];
        
        if ($userId) {
            $cacheFile = CACHE_PATH . "/ai_conversation_{$userId}.json";
            if (file_exists($cacheFile)) {
                unlink($cacheFile);
            }
        }
    }
    
    /**
     * Get sentiment emoji
     */
    private function getSentimentEmoji(string $sentiment): string {
        switch($sentiment) {
            case 'positive':
                return '😊';
            case 'negative':
                return '😞';
            default:
                return '😐';
        }
    }
    
    /**
     * Log errors
     */
    private function logError(string $message): void {
        $logFile = LOGS_PATH . '/ai_errors_' . date('Y-m-d') . '.log';
        $timestamp = date('Y-m-d H:i:s');
        file_put_contents($logFile, "[{$timestamp}] {$message}\n", FILE_APPEND);
    }
    
    /**
     * Set model
     */
    public function setModel(string $model): void {
        $this->model = $model;
    }
    
    /**
     * Get available models
     */
    public function getAvailableModels(): array {
        return [
            'gemini-pro' => 'Gemini Pro (Text)',
            'gemini-pro-vision' => 'Gemini Pro Vision (Text + Image)'
        ];
    }
}
