#!/usr/bin/env php
<?php
// scripts/cleanup_old_translations.php
// Limpia registros antiguos de la cola de traducción

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/logger.php';

custom_log("[CLEANUP] Iniciando limpieza de registros antiguos");

try {
    // Configurar días de retención
    $retentionDays = 7;
    
    // Eliminar registros completados o fallidos antiguos
    $stmt = $pdo->prepare("
        DELETE FROM translation_queue 
        WHERE status IN ('completed', 'failed') 
          AND created_at < DATE_SUB(NOW(), INTERVAL ? DAY)
    ");
    $stmt->execute([$retentionDays]);
    $deleted = $stmt->rowCount();
    
    custom_log("[CLEANUP] Eliminados {$deleted} registros antiguos (>{$retentionDays} días)");
    
    // Obtener estadísticas actuales
    $stmt = $pdo->query("
        SELECT 
            status,
            COUNT(*) as count
        FROM translation_queue
        GROUP BY status
    ");
    $stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    custom_log("[CLEANUP] Estadísticas actuales:");
    foreach ($stats as $stat) {
        custom_log("[CLEANUP]   {$stat['status']}: {$stat['count']}");
    }
    
    // Verificar trabajos atascados (en processing por más de 10 minutos)
    $stmt = $pdo->prepare("
        UPDATE translation_queue 
        SET status = 'pending',
            worker_id = NULL,
            processing_started_at = NULL
        WHERE status = 'processing' 
          AND processing_started_at < DATE_SUB(NOW(), INTERVAL 10 MINUTE)
    ");
    $stmt->execute();
    $reset = $stmt->rowCount();
    
    if ($reset > 0) {
        custom_log("[CLEANUP] Reiniciados {$reset} trabajos atascados");
    }
    
    custom_log("[CLEANUP] Limpieza completada");
    
} catch (Exception $e) {
    custom_log("[CLEANUP] Error: " . $e->getMessage());
    exit(1);
}

exit(0);
