<?php

require_once __DIR__ . '/src/Translate.php';

function translateText(string $text, string $sourceLang, string $targetLang): ?string
{
    $translator = new \src\Translate();
    return $translator->translate($text, $sourceLang, $targetLang);
}

function detectLanguage(string $text): ?string
{
    $translator = new \src\Translate();
    return $translator->detectLanguage($text);
}

function getActiveLanguages(): array
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->query("SELECT * FROM supported_languages WHERE is_active = 1 ORDER BY language_name");
    return $stmt->fetchAll();
}

function queueTranslation(string $platform, int $chatId, int $userId, string $text, string $sourceLang): int
{
    $pdo = getDbConnection();
    
    $stmt = $pdo->prepare("
        INSERT INTO translation_queue 
        (platform, chat_id, user_id, text_to_translate, source_lang, status, attempts, created_at)
        VALUES (?, ?, ?, ?, ?, 'pending', 0, NOW())
    ");
    $stmt->execute([$platform, $chatId, $userId, $text, $sourceLang]);
    
    return (int) $pdo->lastInsertId();
}

function translateAndSendToPlatform(string $platform, int $chatId, string $htmlContent): void
{
    $translator = new \src\Translate();
    
    $converterClass = $platform === 'discord' 
        ? \Discord\Converters\HtmlToDiscordMarkdownConverter::class
        : \Telegram\Converters\HtmlToTelegramHtmlConverter::class;
    
    $converter = new $converterClass();
    $textContent = strip_tags($converter->convert($htmlContent));
    
    $sourceLang = $translator->detectLanguage($textContent) ?? 'es';
    
    $languages = getActiveLanguages();
    $targetLangs = array_filter($languages, fn($l) => $l['language_code'] !== $sourceLang);
    
    $translations = [];
    foreach ($targetLangs as $lang) {
        $translations[$lang['language_code']] = $translator->translate($textContent, $sourceLang, $lang['language_code']);
    }
    
    if ($platform === 'discord') {
        $sender = new \Discord\DiscordSender();
        $actions = new \Discord\Actions\DiscordActions();
        $actions->sendWithTranslation((string)$chatId, $htmlContent, $translations);
    } else {
        $sender = new \Telegram\TelegramSender();
        $actions = new \Telegram\Actions\TelegramActions();
        $actions->sendWithTranslation((int)$chatId, $htmlContent, $translations);
    }
}
