import asyncio
import os
from bullmq import Queue
import logging

# Configurar logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def bullmq_delete_all_job(worker: str, redis_url: str = None):
    """
    Función para eliminar todos los jobs de una cola BullMQ específica.
    Esta función remueve los jobs de Redis para detener abruptamente el consumo de nuevos servicios.
    
    Args:
        worker: Nombre de la cola de trabajos
        redis_url: URL de Redis (opcional, usa variable de entorno por defecto)
    
    Returns:
        dict: Diccionario con la cantidad de jobs eliminados por estado
    """
    if redis_url is None:
        redis_url = os.environ.get('REDIS_HOST', 'redis://192.168.1.163:6379')
    
    async def delete_all_jobs():
        try:
            # Crear la cola
            queue = Queue(worker, {"connection": redis_url})
            
            result = {
                "waiting": 0,
                "active": 0,
                "completed": 0,
                "failed": 0,
                "delayed": 0,
                "total": 0
            }
            
            # Eliminar jobs en diferentes estados
            states_to_clean = ["waiting", "active", "completed", "failed", "delayed"]
            
            for state in states_to_clean:
                try:
                    # Limpiar jobs usando clean() con timestamp 0 para eliminar todos
                    # y limit alto para asegurar que todos sean eliminados
                    cleaned_count = await queue.clean(0, 10000, state)
                    result[state] = cleaned_count
                    result["total"] += cleaned_count
                    
                    if cleaned_count > 0:
                        logger.info(f"Deleted {cleaned_count} jobs in '{state}' state from worker '{worker}'")
                except Exception as e:
                    logger.warning(f"Error cleaning '{state}' jobs from worker '{worker}': {str(e)}")
                    result[state] = 0
            
            # También eliminar jobs pausados si existen
            try:
                paused_count = await queue.clean(0, 10000, "paused")
                result["paused"] = paused_count
                result["total"] += paused_count
                
                if paused_count > 0:
                    logger.info(f"Deleted {paused_count} paused jobs from worker '{worker}'")
            except Exception as e:
                logger.warning(f"Error cleaning paused jobs from worker '{worker}': {str(e)}")
                result["paused"] = 0
            
            logger.info(f"Total jobs deleted from worker '{worker}': {result['total']}")
            
            # Cerrar la conexión
            await queue.close()
            
            return result
            
        except Exception as e:
            logger.error(f"Error deleting all jobs from worker '{worker}': {str(e)}")
            raise e
    
    # Ejecutar la función asíncrona
    try:
        delete_result = asyncio.run(delete_all_jobs())
        return delete_result
    except Exception as e:
        logger.error(f"Failed to delete all jobs: {str(e)}")
        raise e

# Función asíncrona para uso en contextos async
async def bullmq_delete_all_job_async(worker: str, redis_url: str = None):
    """
    Versión asíncrona de bullmq_delete_all_job para uso en contextos async.
    
    Args:
        worker: Nombre de la cola de trabajos
        redis_url: URL de Redis (opcional, usa variable de entorno por defecto)
    
    Returns:
        dict: Diccionario con la cantidad de jobs eliminados por estado
    """
    if redis_url is None:
        redis_url = os.environ.get('REDIS_HOST', 'redis://192.168.1.163:6379')
    
    try:
        # Crear la cola
        queue = Queue(worker, {"connection": redis_url})
        
        result = {
            "waiting": 0,
            "active": 0,
            "completed": 0,
            "failed": 0,
            "delayed": 0,
            "total": 0
        }
        
        # Eliminar jobs en diferentes estados
        states_to_clean = ["waiting", "active", "completed", "failed", "delayed"]
        
        for state in states_to_clean:
            try:
                # Limpiar jobs usando clean() con timestamp 0 para eliminar todos
                # y limit alto para asegurar que todos sean eliminados
                cleaned_count = await queue.clean(0, 10000, state)
                result[state] = cleaned_count
                result["total"] += cleaned_count
                
                if cleaned_count > 0:
                    logger.info(f"Deleted {cleaned_count} jobs in '{state}' state from worker '{worker}'")
            except Exception as e:
                logger.warning(f"Error cleaning '{state}' jobs from worker '{worker}': {str(e)}")
                result[state] = 0
        
        # También eliminar jobs pausados si existen
        try:
            paused_count = await queue.clean(0, 10000, "paused")
            result["paused"] = paused_count
            result["total"] += paused_count
            
            if paused_count > 0:
                logger.info(f"Deleted {paused_count} paused jobs from worker '{worker}'")
        except Exception as e:
            logger.warning(f"Error cleaning paused jobs from worker '{worker}': {str(e)}")
            result["paused"] = 0
        
        logger.info(f"Total jobs deleted from worker '{worker}': {result['total']}")
        
        # Cerrar la conexión
        await queue.close()
        
        return result
        
    except Exception as e:
        logger.error(f"Error deleting all jobs from worker '{worker}': {str(e)}")
        raise e
