# #!/usr/bin/env python3
# """
# Script para probar backup real de BullMQ con MongoDB real
# """
# import sys
# import os
# from datetime import datetime, timezone

# # Agregar el directorio principal al path para imports
# sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

# try:
#     from tredops_eval.connect import db
# except ImportError:
#     db = None
    
# from tredops_strategy_worker.bullmaq_backup import bullmq_backup, list_backups, mongodb_collection_backup
# from tredops_strategy_worker.bullmq_sender import bullmq_sender
# import time

# def test_real_backup():
#     """Test de backup con base de datos MongoDB real."""
#     print("=== Test de Backup Real con MongoDB ===")
    
#     # Verificar conexión a la base de datos
#     if db is None:
#         print("❌ Error: No se pudo conectar a la base de datos MongoDB")
#         return False
    
#     print(f"✅ Conectado a MongoDB")
#     print(f"Base de datos: {db.name}")
#     print(f"Colección de backup: {mongodb_collection_backup}")
    
#     # Crear algunos jobs de prueba para hacer backup
#     test_queues = ["real_backup_test_1", "real_backup_test_2"]
#     job_ids = []
    
#     print(f"\n📤 Creando jobs de prueba en colas: {test_queues}")
#     for i, queue_name in enumerate(test_queues):
#         try:
#             job_id = bullmq_sender(
#                 worker=queue_name,
#                 priority=5 + i,
#                 delay_sec=3,  # Delay para asegurar que estén en estado "delayed"
#                 message={
#                     "real_backup_test": True,
#                     "queue_index": i,
#                     "data": f"Test data for real backup {i}",
#                     "timestamp": datetime.now(timezone.utc).isoformat()
#                 },
#                 job_id=f"real_backup_job_{i}_{int(time.time())}"
#             )
#             job_ids.append(job_id)
#             print(f"  ✅ Job creado: {job_id} en cola '{queue_name}'")
            
#         except Exception as e:
#             print(f"  ❌ Error creando job en cola '{queue_name}': {e}")
    
#     if not job_ids:
#         print("❌ No se crearon jobs para hacer backup")
#         return False
    
#     print(f"\n⏳ Esperando 2 segundos para que se registren los jobs...")
#     time.sleep(2)
    
#     # Hacer backup real
#     backup_name = f"real_test_backup_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}"
    
#     print(f"\n💾 Creando backup: {backup_name}")
#     backup_result = bullmq_backup(
#         db=db,
#         queue_names=test_queues,
#         backup_name=backup_name
#     )
    
#     # Mostrar resultado del backup
#     print(f"\n📊 Resultado del backup:")
#     print(f"  Status: {backup_result.get('status', 'unknown')}")
#     print(f"  Backup ID: {backup_result.get('backup_id', 'N/A')}")
#     print(f"  MongoDB ID: {backup_result.get('mongodb_id', 'N/A')}")
#     print(f"  Total jobs: {backup_result.get('total_jobs', 0)}")
#     print(f"  Total queues: {backup_result.get('total_queues', 0)}")
#     print(f"  Message: {backup_result.get('message', 'N/A')}")
    
#     if backup_result.get('status') != 'success':
#         print(f"❌ Error en backup: {backup_result.get('error', 'Unknown error')}")
#         return False
    
#     # Verificar que se guardó en la base de datos
#     print(f"\n🔍 Verificando backup en base de datos...")
#     try:
#         collection = db[mongodb_collection_backup]
        
#         # Buscar el backup recién creado
#         saved_backup = collection.find_one({"backup_id": backup_name})
        
#         if saved_backup:
#             print(f"  ✅ Backup encontrado en MongoDB")
#             print(f"  MongoDB _id: {saved_backup['_id']}")
#             print(f"  Fecha creación: {saved_backup['created_at']}")
#             print(f"  Total jobs en backup: {saved_backup['total_jobs']}")
#             print(f"  Colas en backup: {list(saved_backup['queues'].keys())}")
            
#             # Mostrar detalles de cada cola
#             for queue_name, queue_data in saved_backup['queues'].items():
#                 if 'error' not in queue_data:
#                     counts = queue_data.get('counts', {})
#                     total_queue_jobs = sum(counts.values())
#                     print(f"    📋 Cola '{queue_name}': {total_queue_jobs} jobs")
#                     for state, count in counts.items():
#                         if count > 0:
#                             print(f"      - {state}: {count}")
#                 else:
#                     print(f"    ❌ Cola '{queue_name}': Error - {queue_data['error']}")
            
#         else:
#             print(f"  ❌ Backup NO encontrado en MongoDB")
#             return False
            
#     except Exception as e:
#         print(f"  ❌ Error verificando backup en DB: {e}")
#         return False
    
#     # Listar todos los backups
#     print(f"\n📋 Listando todos los backups en la base de datos:")
#     try:
#         backups_list = list_backups(db)
#         print(f"  Total backups encontrados: {len(backups_list)}")
        
#         for backup in backups_list[:5]:  # Mostrar solo los primeros 5
#             print(f"    🗂️  {backup['backup_id']} - {backup['created_at']} ({backup['total_jobs']} jobs)")
            
#         if len(backups_list) > 5:
#             print(f"    ... y {len(backups_list) - 5} backups más")
            
#     except Exception as e:
#         print(f"  ❌ Error listando backups: {e}")
    
#     print(f"\n✅ Test de backup real completado exitosamente!")
#     print(f"🎯 El backup '{backup_name}' está ahora guardado en tu base de datos MongoDB")
#     print(f"🔧 Puedes verificarlo directamente en MongoDB en la colección: {mongodb_collection_backup}")
    
#     return True

# def show_backup_details(backup_id=None):
#     """Mostrar detalles de un backup específico o el más reciente."""
#     if db is None:
#         print("❌ No se pudo conectar a la base de datos")
#         return
    
#     try:
#         collection = db[mongodb_collection_backup]
        
#         if backup_id:
#             backup = collection.find_one({"backup_id": backup_id})
#             if not backup:
#                 print(f"❌ Backup '{backup_id}' no encontrado")
#                 return
#         else:
#             # Obtener el backup más reciente
#             backup = collection.find_one(sort=[("created_at", -1)])
#             if not backup:
#                 print("❌ No hay backups en la base de datos")
#                 return
        
#         print(f"\n📄 Detalles del backup: {backup['backup_id']}")
#         print(f"   Creado: {backup['created_at']}")
#         print(f"   Total jobs: {backup['total_jobs']}")
#         print(f"   Total queues: {backup['total_queues']}")
        
#         print(f"\n📋 Colas y jobs:")
#         for queue_name, queue_data in backup.get('queues', {}).items():
#             if 'error' not in queue_data:
#                 counts = queue_data.get('counts', {})
#                 total = sum(counts.values())
#                 print(f"   🔹 {queue_name}: {total} jobs")
#                 for state, count in counts.items():
#                     if count > 0:
#                         print(f"      - {state}: {count}")
#             else:
#                 print(f"   ❌ {queue_name}: Error")
                
#     except Exception as e:
#         print(f"❌ Error mostrando detalles: {e}")

# if __name__ == "__main__":
#     import argparse
    
#     parser = argparse.ArgumentParser(description="Test de backup real de BullMQ")
#     parser.add_argument('--show', type=str, help='Mostrar detalles de un backup específico')
#     parser.add_argument('--list', action='store_true', help='Solo listar backups existentes')
    
#     args = parser.parse_args()
    
#     if args.list:
#         # Solo listar backups
#         if db:
#             backups_list = list_backups(db)
#             print(f"📋 Backups disponibles ({len(backups_list)}):")
#             for backup in backups_list:
#                 print(f"  🗂️  {backup['backup_id']} - {backup['created_at']} ({backup['total_jobs']} jobs)")
#         else:
#             print("❌ No se pudo conectar a la base de datos")
    
#     elif args.show:
#         # Mostrar detalles de backup específico
#         show_backup_details(args.show)
    
#     else:
#         # Ejecutar test completo
#         success = test_real_backup()
#         exit(0 if success else 1)