#!/usr/bin/php
<?php
// run_manual_translation.php

// Log de depuración muy temprano
file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - Script started.\n", FILE_APPEND);

// This script is called from the command line, not by a web server.
if (php_sapi_name() !== 'cli') {
    file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - Not CLI, exiting.\n", FILE_APPEND);
    die("This script can only be run from the command line.");
}
file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - Is CLI.\n", FILE_APPEND);

// Need to bootstrap the application to get config, db, etc.
// We need to manually set the environment if it's not passed
if (getenv('APP_ENVIRONMENT') === false && isset($argv[5])) {
    putenv('APP_ENVIRONMENT=' . $argv[5]);
    file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - APP_ENVIRONMENT set to: " . $argv[5] . "\n", FILE_APPEND);
} else {
    file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - APP_ENVIRONMENT already set or not provided in argv[5]. Current: " . getenv('APP_ENVIRONMENT') . "\n", FILE_APPEND);
}

file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - Requiring config.php.\n", FILE_APPEND);
require_once __DIR__ . '/config/config.php';
file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - config.php required.\n", FILE_APPEND);

file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - Requiring autoload.php.\n", FILE_APPEND);
require_once __DIR__ . '/vendor/autoload.php';
file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - autoload.php required.\n", FILE_APPEND);

file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - Requiring db.php.\n", FILE_APPEND);
require_once __DIR__ . '/includes/db.php';
file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - db.php required.\n", FILE_APPEND);

file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - Requiring logger.php.\n", FILE_APPEND);
require_once __DIR__ . '/includes/logger.php'; // Añadido para custom_log()
file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - logger.php required.\n", FILE_APPEND);

file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - Requiring Translate.php.\n", FILE_APPEND);
require_once __DIR__ . '/src/Translate.php';
file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - Translate.php required.\n", FILE_APPEND);

// Direct logging function for this script
function direct_log($message) {
    $logFile = __DIR__ . '/logs/custom_debug.log'; // Path relative to this script
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[" . $timestamp . "] [DIRECT_LOG] " . $message . "\n", FILE_APPEND);
}


if ($argc < 5) {
    file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - Not enough arguments, exiting.\n", FILE_APPEND);
    die("Usage: php run_manual_translation.php <messageId> <targetLang> <userId> <channelId> [environment]\n");
}

$messageId = $argv[1];
$targetLang = $argv[2];
$userId = $argv[3];
$channelId = $argv[4];

file_put_contents(__DIR__ . '/logs/early_debug.log', date('Y-m-d H:i:s') . " - Arguments parsed. Calling direct_log for the first time.\n", FILE_APPEND);
direct_log("[MANUAL_TRANSLATE_WORKER] Iniciando para msg {" . $messageId . "} a {" . $targetLang . "}");

try {
    $stmt = $pdo->prepare("SELECT message_content FROM recurrent_messages WHERE id = ?");
    $stmt->execute([$messageId]);
    $originalHtml = $stmt->fetchColumn();

    if ($originalHtml) {
        $translator = new Translate();
        $textContent = strip_tags(html_entity_decode($originalHtml));
        $sourceLang = $translator->detectLanguage($textContent);

        if ($sourceLang) {
            direct_log("[MANUAL_TRANSLATE_WORKER] Idioma detectado: {" . $sourceLang . "}. Traduciendo a {" . $targetLang . "}.");
            $translatedHtml = $translator->translateHtml($originalHtml, $sourceLang, $targetLang);
            
            if ($translatedHtml && $translatedHtml !== $originalHtml) {
                $sender = new DiscordSender(DISCORD_BOT_TOKEN);
                $mention = "<@{"
 . $userId . "}>;
                $finalContent = $mention . " *Traducción a {" . $targetLang . "}:*\n" . $translatedHtml;
                $sender->sendMessage($channelId, $finalContent);
                direct_log("[MANUAL_TRANSLATE_WORKER] Traducción enviada con éxito.");
            } else {
                direct_log("[MANUAL_TRANSLATE_WORKER] La traducción falló o resultó en el mismo texto. No se envía nada.");
            }
        } else {
             direct_log("[MANUAL_TRANSLATE_WORKER] No se pudo detectar el idioma de origen.");
        }
    } else {
        direct_log("[MANUAL_TRANSLATE_WORKER] No se encontró la plantilla con ID {" . $messageId . "}.");
    }
} catch (Throwable $e) {
    direct_log("[MANUAL_TRANSLATE_WORKER] ERROR FATAL: " . $e->getMessage() . " en " . $e->getFile() . ":" . $e->getLine());
}
?>
