<?php

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/src/Translate.php';
require_once __DIR__ . '/telegram/TelegramSender.php';
require_once __DIR__ . '/discord/DiscordSender.php';

define('DAEMON_MODE', php_sapi_name() === 'cli' && !isset($_GET['run']));
define('SLEEP_INTERVAL', 5);

function processTranslationQueue(): array
{
    $pdo = getDbConnection();
    $translate = new \src\Translate();
    
    $stmt = $pdo->query("SELECT language_code FROM supported_languages WHERE is_active = 1");
    $activeLanguages = $stmt->fetchAll(\PDO::FETCH_COLUMN);
    
    $stmt = $pdo->prepare("
        SELECT * FROM translation_queue 
        WHERE status = 'pending' 
        ORDER BY created_at ASC 
        LIMIT 10
        FOR UPDATE SKIP LOCKED
    ");
    $stmt->execute();
    $queueItems = $stmt->fetchAll();
    
    $results = ['processed' => 0, 'completed' => 0, 'failed' => 0];
    
    foreach ($queueItems as $item) {
        $pdo->prepare("UPDATE translation_queue SET status = 'processing', attempts = attempts + 1 WHERE id = ?")
            ->execute([$item['id']]);
        
        try {
            $sourceLang = $item['source_lang'];
            $targetLangs = array_filter($activeLanguages, fn($l) => $l !== $sourceLang);
            
            $translatedTexts = [];
            foreach ($targetLangs as $lang) {
                $translatedTexts[$lang] = $translate->translate(
                    $item['text_to_translate'],
                    $sourceLang,
                    $lang
                );
            }
            
            sendTranslationToUser($item, $translatedTexts);
            
            $pdo->prepare("
                UPDATE translation_queue 
                SET status = 'completed', processed_at = NOW() 
                WHERE id = ?
            ")->execute([$item['id']]);
            
            $results['completed']++;
            
        } catch (\Exception $e) {
            $attempts = $item['attempts'] + 1;
            
            if ($attempts >= 5) {
                $pdo->prepare("
                    UPDATE translation_queue 
                    SET status = 'failed', error_message = ?, attempts = ? 
                    WHERE id = ?
                ")->execute([$e->getMessage(), $attempts, $item['id']]);
                $results['failed']++;
            } else {
                $pdo->prepare("UPDATE translation_queue SET status = 'pending', attempts = ? WHERE id = ?")
                    ->execute([$attempts, $item['id']]);
            }
        }
        
        $results['processed']++;
    }
    
    return $results;
}

function sendTranslationToUser(array $item, array $translatedTexts): void
{
    $platform = $item['platform'];
    $chatId = $item['chat_id'];
    $originalText = $item['text_to_translate'];
    $sourceLang = strtoupper($item['source_lang']);
    
    if ($platform === 'telegram') {
        $sender = new \Telegram\TelegramSender();
        
        $message = "🌐 <b>Traducción</b>\n\n";
        $message .= "<i>Original ({$sourceLang}):</i>\n";
        $message .= $originalText . "\n\n";
        
        foreach ($translatedTexts as $lang => $text) {
            if ($text) {
                $message .= "<i>" . strtoupper($lang) . ":</i>\n";
                $message .= $text . "\n\n";
            }
        }
        
        $sender->sendMessage($chatId, $message);
        
    } elseif ($platform === 'discord') {
        $sender = new \Discord\DiscordSender();
        
        $embed = [
            'title' => '🌐 Traducción',
            'description' => $originalText,
            'color' => 3066993,
            'fields' => []
        ];
        
        foreach ($translatedTexts as $lang => $text) {
            if ($text) {
                $embed['fields'][] = [
                    'name' => strtoupper($lang),
                    'value' => mb_substr($text, 0, 1024),
                    'inline' => false
                ];
            }
        }
        
        $sender->sendMessage($chatId, '', $embed);
    }
}

function logMessage(string $message): void
{
    echo "[" . date('Y-m-d H:i:s') . "] " . $message . PHP_EOL;
}

if (DAEMON_MODE) {
    logMessage("Translation Queue Worker started");
    
    while (true) {
        try {
            $results = processTranslationQueue();
            
            if ($results['processed'] > 0) {
                logMessage("Processed: {$results['processed']}, Completed: {$results['completed']}, Failed: {$results['failed']}");
            }
        } catch (Exception $e) {
            logMessage("Error: " . $e->getMessage());
        }
        
        sleep(SLEEP_INTERVAL);
    }
} else {
    $results = processTranslationQueue();
    echo "Translation Queue - Processed: {$results['processed']}, Completed: {$results['completed']}, Failed: {$results['failed']}\n";
}
