#!/usr/bin/env php
<?php
// scripts/translation_stats.php
// Muestra estadísticas del sistema de traducción

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../src/TranslationCache.php';

echo "\n=== ESTADÍSTICAS DEL SISTEMA DE TRADUCCIÓN ===\n\n";

// Estadísticas de la cola
echo "📊 COLA DE TRADUCCIÓN:\n";
$stmt = $pdo->query("
    SELECT 
        status,
        COUNT(*) as count,
        AVG(attempts) as avg_attempts
    FROM translation_queue
    GROUP BY status
");
$queueStats = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($queueStats as $stat) {
    $avgAttempts = round($stat['avg_attempts'], 2);
    echo "  {$stat['status']}: {$stat['count']} (avg attempts: {$avgAttempts})\n";
}

// Total de traducciones hoy
$stmt = $pdo->query("
    SELECT COUNT(*) as count
    FROM translation_queue
    WHERE DATE(created_at) = CURDATE()
");
$todayCount = $stmt->fetchColumn();
echo "\n  Traducciones hoy: {$todayCount}\n";

// Traducciones por plataforma
echo "\n📱 POR PLATAFORMA:\n";
$stmt = $pdo->query("
    SELECT 
        platform,
        status,
        COUNT(*) as count
    FROM translation_queue
    WHERE DATE(created_at) = CURDATE()
    GROUP BY platform, status
");
$platformStats = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($platformStats as $stat) {
    echo "  {$stat['platform']} - {$stat['status']}: {$stat['count']}\n";
}

// Workers activos
echo "\n👷 WORKERS ACTIVOS:\n";
$workerCount = 0;
exec("ps aux | grep -c '[T]ranslationWorker'", $output, $returnCode);
if ($returnCode === 0 && isset($output[0])) {
    $workerCount = (int)$output[0];
}
echo "  Workers en ejecución: {$workerCount}\n";

// Workers únicos en la BD
$stmt = $pdo->query("
    SELECT DISTINCT worker_id, COUNT(*) as jobs
    FROM translation_queue
    WHERE status = 'processing'
    GROUP BY worker_id
");
$activeWorkers = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!empty($activeWorkers)) {
    echo "\n  Workers procesando:\n";
    foreach ($activeWorkers as $worker) {
        echo "    - {$worker['worker_id']}: {$worker['jobs']} job(s)\n";
    }
}

// Estadísticas de caché
echo "\n💾 CACHÉ DE TRADUCCIONES:\n";
try {
    $cache = new TranslationCache();
    $cacheStats = $cache->getStats();
    
    if ($cacheStats['enabled']) {
        echo "  Estado: Habilitado ✓\n";
        echo "  Hits: {$cacheStats['hits']}\n";
        echo "  Misses: {$cacheStats['misses']}\n";
        echo "  Total requests: {$cacheStats['total_requests']}\n";
        echo "  Hit rate: {$cacheStats['hit_rate']}%\n";
    } else {
        echo "  Estado: Deshabilitado ✗\n";
    }
} catch (Exception $e) {
    echo "  Error: " . $e->getMessage() . "\n";
}

// Tiempos promedio
echo "\n⏱️  RENDIMIENTO:\n";
$stmt = $pdo->query("
    SELECT 
        AVG(TIMESTAMPDIFF(SECOND, created_at, processed_at)) as avg_time,
        MIN(TIMESTAMPDIFF(SECOND, created_at, processed_at)) as min_time,
        MAX(TIMESTAMPDIFF(SECOND, created_at, processed_at)) as max_time
    FROM translation_queue
    WHERE status = 'completed'
      AND DATE(created_at) = CURDATE()
      AND processed_at IS NOT NULL
");
$perfStats = $stmt->fetch(PDO::FETCH_ASSOC);

if ($perfStats && $perfStats['avg_time'] !== null) {
    echo "  Tiempo promedio: " . round($perfStats['avg_time'], 2) . " segundos\n";
    echo "  Tiempo mínimo: " . round($perfStats['min_time'], 2) . " segundos\n";
    echo "  Tiempo máximo: " . round($perfStats['max_time'], 2) . " segundos\n";
} else {
    echo "  No hay datos de rendimiento para hoy\n";
}

echo "\n" . str_repeat("=", 50) . "\n\n";
