<?php

// Cargar logger si está disponible
if (file_exists(__DIR__ . '/../includes/logger.php')) {
    require_once __DIR__ . '/../includes/logger.php';
}

// Función fallback si custom_log no está definida
if (!function_exists('custom_log')) {
    function custom_log($message) {
        error_log($message);
    }
}


class TranslationCache {
    private $redis;
    private $ttl = 604800; // 7 días por defecto
    private $enabled = true;
    private $prefix = 'trans:';
    
    public function __construct() {
        // Verificar si el caché está habilitado
        $this->enabled = ($_ENV['TRANSLATION_CACHE_ENABLED'] ?? 'true') === 'true';
        
        if (!$this->enabled) {
            custom_log("[CACHE] Caché de traducciones deshabilitado");
            return;
        }
        
        // Configurar TTL desde environment
        if (isset($_ENV['TRANSLATION_CACHE_TTL'])) {
            $this->ttl = (int)$_ENV['TRANSLATION_CACHE_TTL'];
        }
        
        try {
            // Intentar conectar a Redis
            $this->redis = new Redis();
            $host = $_ENV['REDIS_HOST'] ?? 'localhost';
            $port = (int)($_ENV['REDIS_PORT'] ?? 6379);
            $password = $_ENV['REDIS_PASSWORD'] ?? null;
            
            $connected = $this->redis->connect($host, $port, 2.0); // 2 segundos timeout
            
            if (!$connected) {
                throw new Exception("No se pudo conectar a Redis en {$host}:{$port}");
            }
            
            // Autenticar si hay password
            if ($password) {
                $this->redis->auth($password);
            }
            
            // Verificar conexión
            $this->redis->ping();
            custom_log("[CACHE] Conectado a Redis en {$host}:{$port}");
            
        } catch (Exception $e) {
            custom_log("[CACHE] Error al conectar a Redis: " . $e->getMessage());
            custom_log("[CACHE] El sistema funcionará sin caché");
            $this->enabled = false;
            $this->redis = null;
        }
    }
    
    /**
     * Obtener traducción del caché
     */
    public function get($text, $source, $target) {
        if (!$this->enabled || !$this->redis) {
            return false;
        }
        
        try {
            $key = $this->generateKey($text, $source, $target);
            $cached = $this->redis->get($key);
            
            if ($cached !== false) {
                $this->incrementHits();
                custom_log("[CACHE] HIT: {$source}->{$target} (key: " . substr($key, 0, 20) . "...)");
                return $cached;
            }
            
            $this->incrementMisses();
            custom_log("[CACHE] MISS: {$source}->{$target}");
            return false;
            
        } catch (Exception $e) {
            custom_log("[CACHE] Error al obtener del caché: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Guardar traducción en el caché
     */
    public function set($text, $source, $target, $translation) {
        if (!$this->enabled || !$this->redis || empty($translation)) {
            return false;
        }
        
        try {
            $key = $this->generateKey($text, $source, $target);
            $result = $this->redis->setex($key, $this->ttl, $translation);
            
            if ($result) {
                custom_log("[CACHE] Guardado: {$source}->{$target} (TTL: {$this->ttl}s)");
            }
            
            return $result;
            
        } catch (Exception $e) {
            custom_log("[CACHE] Error al guardar en caché: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Generar clave única para la traducción
     */
    private function generateKey($text, $source, $target) {
        // Normalizar texto para mejor hit rate
        $normalized = trim(strtolower($text));
        $hash = md5($normalized . '|' . $source . '|' . $target);
        return $this->prefix . $hash;
    }
    
    /**
     * Incrementar contador de hits
     */
    private function incrementHits() {
        if (!$this->enabled || !$this->redis) {
            return;
        }
        
        try {
            $this->redis->incr($this->prefix . 'stats:hits');
        } catch (Exception $e) {
            // Ignorar errores en estadísticas
        }
    }
    
    /**
     * Incrementar contador de misses
     */
    private function incrementMisses() {
        if (!$this->enabled || !$this->redis) {
            return;
        }
        
        try {
            $this->redis->incr($this->prefix . 'stats:misses');
        } catch (Exception $e) {
            // Ignorar errores en estadísticas
        }
    }
    
    /**
     * Obtener estadísticas del caché
     */
    public function getStats() {
        if (!$this->enabled || !$this->redis) {
            return [
                'enabled' => false,
                'hits' => 0,
                'misses' => 0,
                'hit_rate' => 0
            ];
        }
        
        try {
            $hits = (int)$this->redis->get($this->prefix . 'stats:hits') ?: 0;
            $misses = (int)$this->redis->get($this->prefix . 'stats:misses') ?: 0;
            $total = $hits + $misses;
            $hitRate = $total > 0 ? round(($hits / $total) * 100, 2) : 0;
            
            return [
                'enabled' => true,
                'hits' => $hits,
                'misses' => $misses,
                'total_requests' => $total,
                'hit_rate' => $hitRate
            ];
            
        } catch (Exception $e) {
            custom_log("[CACHE] Error al obtener estadísticas: " . $e->getMessage());
            return [
                'enabled' => true,
                'error' => $e->getMessage()
            ];
        }
    }
    
    /**
     * Limpiar todo el caché de traducciones
     */
    public function clear() {
        if (!$this->enabled || !$this->redis) {
            return false;
        }
        
        try {
            $keys = $this->redis->keys($this->prefix . '*');
            if (!empty($keys)) {
                $deleted = $this->redis->del($keys);
                custom_log("[CACHE] Limpiado: {$deleted} claves eliminadas");
                return $deleted;
            }
            return 0;
            
        } catch (Exception $e) {
            custom_log("[CACHE] Error al limpiar caché: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Verificar si el caché está habilitado y funcionando
     */
    public function isEnabled() {
        return $this->enabled && $this->redis !== null;
    }
}
