from .bullmq_flow import bullmq_flow, bullmq_flow_async, bullmq_flow_status
from .bullmq_consumer import consumer_bullmq
from .bullmq_sender import bullmq_sender
import pytest
import asyncio
import os
import threading
import time
from datetime import datetime

def flow_parent_worker(message):
    """Worker function para procesar jobs padre."""
    print(f"Processing PARENT job: {message}")
    # Almacenar el mensaje procesado para verificar en el test
    if hasattr(flow_parent_worker, 'processed_messages'):
        flow_parent_worker.processed_messages.append(message)
    else:
        flow_parent_worker.processed_messages = [message]
    
    return {"status": "parent_processed", "flow_id": message.get("_flow_id"), "data": message}

def flow_child_worker(message):
    """Worker function para procesar jobs hijos."""
    print(f"Processing CHILD job: {message}")
    # Almacenar el mensaje procesado para verificar en el test
    if hasattr(flow_child_worker, 'processed_messages'):
        flow_child_worker.processed_messages.append(message)
    else:
        flow_child_worker.processed_messages = [message]
    
    return {"status": "child_processed", "parent_id": message.get("_parent_job_id"), "data": message}

redis_url = os.environ.get('REDIS_HOST', 'redis://192.168.1.163:6379')

def test_bullmq_flow_basic():
    """Test básico para crear un flow con job padre e hijos."""
    # Limpiar mensajes previos
    flow_parent_worker.processed_messages = []
    flow_child_worker.processed_messages = []
    
    # Configuración del flow
    flow_config = {
        "name": "test-parent-job",
        "queueName": "test_parents",
        "data": {"message": "Parent job data", "test_id": "flow_basic_001"},
        "opts": {"priority": 8},
        "children": [
            {
                "name": "test-child-1",
                "queueName": "test_children", 
                "data": {"x": 1, "task": "child_task_1"},
                "opts": {"priority": 7}
            },
            {
                "name": "test-child-2",
                "queueName": "test_children",
                "data": {"x": 2, "task": "child_task_2"},
                "opts": {"priority": 6}
            }
        ]
    }
    
    # Crear el flow
    flow_result = bullmq_flow(flow_config)
    
    # Verificaciones básicas del flow
    assert flow_result["status"] == "success", f"Flow creation failed: {flow_result}"
    assert "flow_id" in flow_result, "Flow ID missing"
    assert "parent_job" in flow_result, "Parent job info missing"
    assert "children" in flow_result, "Children info missing"
    assert flow_result["children_count"] == 2, "Incorrect children count"
    assert flow_result["children_success"] == 2, "Not all children created successfully"
    
    # Verificar información del job padre
    parent_info = flow_result["parent_job"]
    assert parent_info["name"] == "test-parent-job", "Parent name incorrect"
    assert parent_info["queue"] == "test_parents", "Parent queue incorrect"
    assert parent_info["priority"] == 8, "Parent priority incorrect"
    assert parent_info["job_id"] is not None, "Parent job ID missing"
    
    # Verificar información de los hijos
    children = flow_result["children"]
    assert len(children) == 2, "Incorrect number of children"
    
    child1 = children[0]
    assert child1["child_name"] == "test-child-1", "Child 1 name incorrect"
    assert child1["child_queue"] == "test_children", "Child 1 queue incorrect"
    assert child1["child_priority"] == 7, "Child 1 priority incorrect"
    assert child1["child_job_id"] is not None, "Child 1 job ID missing"
    
    child2 = children[1]
    assert child2["child_name"] == "test-child-2", "Child 2 name incorrect"
    assert child2["child_queue"] == "test_children", "Child 2 queue incorrect"
    assert child2["child_priority"] == 6, "Child 2 priority incorrect"
    assert child2["child_job_id"] is not None, "Child 2 job ID missing"
    
    print(f"✅ Flow created successfully: {flow_result['flow_id']}")
    print(f"   Parent: {parent_info['job_id']} in {parent_info['queue']}")
    print(f"   Children: {len(children)} jobs created")

def test_bullmq_flow_with_delays():
    """Test de flow con delays en los jobs hijos."""
    # Limpiar mensajes previos
    flow_parent_worker.processed_messages = []
    flow_child_worker.processed_messages = []
    
    # Configuración del flow con delays
    flow_config = {
        "name": "delayed-parent-job",
        "queueName": "test_delay_parents",
        "data": {"message": "Parent with delayed children", "test_id": "flow_delay_001"},
        "children": [
            {
                "name": "immediate-child",
                "queueName": "test_delay_children",
                "data": {"delay_type": "immediate", "x": 1},
                "opts": {"priority": 8}  # Sin delay
            },
            {
                "name": "delayed-child",
                "queueName": "test_delay_children", 
                "data": {"delay_type": "delayed", "x": 2},
                "opts": {
                    "delay": 3000,  # 3 segundos en milisegundos
                    "priority": 9
                }
            }
        ]
    }
    
    # Crear consumers para procesar los jobs
    def run_delay_parent_consumer():
        try:
            consumer_bullmq(worker="test_delay_parents", function_process=flow_parent_worker)
        except KeyboardInterrupt:
            pass
    
    def run_delay_child_consumer():
        try:
            consumer_bullmq(worker="test_delay_children", function_process=flow_child_worker)
        except KeyboardInterrupt:
            pass
    
    # Iniciar consumers en threads separados
    parent_thread = threading.Thread(target=run_delay_parent_consumer)
    parent_thread.daemon = True
    parent_thread.start()
    
    child_thread = threading.Thread(target=run_delay_child_consumer)
    child_thread.daemon = True
    child_thread.start()
    
    print("🔍 DELAY TEST - Check BullMQ Dashboard now:")
    print("  - Queue 'test_delay_parents': Should show parent job")
    print("  - Queue 'test_delay_children': Should show immediate child in WAITING and delayed child in DELAYED")
    print("  - Wait 10 seconds to see jobs processing with logs...")
    
    # Crear el flow
    flow_result = bullmq_flow(flow_config)
    
    # Verificaciones
    assert flow_result["status"] == "success", f"Flow creation failed: {flow_result}"
    assert flow_result["children_count"] == 2, "Incorrect children count"
    assert flow_result["children_success"] == 2, "Not all children created successfully"
    
    # Verificar que el delay se procesó correctamente
    children = flow_result["children"]
    immediate_child = next(c for c in children if c["child_name"] == "immediate-child")
    delayed_child = next(c for c in children if c["child_name"] == "delayed-child")
    
    assert immediate_child["child_delay"] == 0, "Immediate child should have no delay"
    assert delayed_child["child_delay"] == 3, "Delayed child should have 3 second delay"
    assert delayed_child["child_priority"] == 9, "Delayed child priority incorrect"
    
    print(f"✅ Flow created successfully: {flow_result['flow_id']}")
    print(f"   Parent: {flow_result['parent_job']['job_id']} in {flow_result['parent_job']['queue']}")
    print(f"   Immediate child: {immediate_child['child_job_id']} (delay: {immediate_child['child_delay']}s)")
    print(f"   Delayed child: {delayed_child['child_job_id']} (delay: {delayed_child['child_delay']}s)")
    
    # Esperar a que se procesen los jobs para ver logs en el dashboard
    print("\n⏱️  Waiting for jobs to process (check dashboard for logs)...")
    time.sleep(8)  # Esperar más tiempo para ver el procesamiento
    
    # Verificar que algunos jobs fueron procesados
    total_processed = len(flow_parent_worker.processed_messages) + len(flow_child_worker.processed_messages)
    print(f"📊 Jobs processed: {total_processed} (Parent: {len(flow_parent_worker.processed_messages)}, Children: {len(flow_child_worker.processed_messages)})")
    
    if total_processed > 0:
        print("✅ Jobs are being processed - check BullMQ dashboard for detailed logs")
    else:
        print("⚠️  No jobs processed yet - jobs should be visible in dashboard queues")
    
    print(f"✅ Delayed flow test completed: {flow_result['flow_id']}")

def test_bullmq_flow_processing():
    """Test para verificar que los jobs del flow son procesados correctamente."""
    # Limpiar mensajes previos
    flow_parent_worker.processed_messages = []
    flow_child_worker.processed_messages = []
    
    # Configuración del flow
    flow_config = {
        "name": "processing-test-parent",
        "queueName": "processing_parents",
        "data": {"message": "Parent for processing test", "test_id": "flow_processing_001"},
        "children": [
            {
                "name": "processing-child-1",
                "queueName": "processing_children",
                "data": {"task": "process_data", "value": 100},
                "opts": {"priority": 5}
            },
            {
                "name": "processing-child-2", 
                "queueName": "processing_children",
                "data": {"task": "validate_data", "value": 200},
                "opts": {"priority": 6}
            }
        ]
    }
    
    # Crear consumers
    def run_parent_consumer():
        try:
            consumer_bullmq(worker="processing_parents", function_process=flow_parent_worker)
        except KeyboardInterrupt:
            pass
    
    def run_child_consumer():
        try:
            consumer_bullmq(worker="processing_children", function_process=flow_child_worker)
        except KeyboardInterrupt:
            pass
    
    # Iniciar consumers en threads separados
    parent_thread = threading.Thread(target=run_parent_consumer)
    parent_thread.daemon = True
    parent_thread.start()
    
    child_thread = threading.Thread(target=run_child_consumer)
    child_thread.daemon = True
    child_thread.start()
    
    # Crear el flow
    flow_result = bullmq_flow(flow_config)
    
    # Verificar que se creó correctamente
    assert flow_result["status"] == "success", f"Flow creation failed: {flow_result}"
    
    # Esperar a que se procesen los mensajes
    time.sleep(5)
    
    # Verificar que el job padre fue procesado
    assert len(flow_parent_worker.processed_messages) >= 1, "Parent job was not processed"
    
    parent_msg = flow_parent_worker.processed_messages[0]
    assert parent_msg["_flow_type"] == "parent", "Parent job type incorrect"
    assert parent_msg["_flow_id"] == flow_result["flow_id"], "Parent flow ID mismatch"
    assert parent_msg["test_id"] == "flow_processing_001", "Parent test ID incorrect"
    
    # Verificar que los jobs hijos fueron procesados
    assert len(flow_child_worker.processed_messages) >= 1, "Child jobs were not processed"
    
    # Verificar metadata de los jobs hijos
    for child_msg in flow_child_worker.processed_messages:
        assert child_msg["_flow_type"] == "child", "Child job type incorrect"
        assert child_msg["_flow_id"] == flow_result["flow_id"], "Child flow ID mismatch"
        assert child_msg["_parent_job_id"] == flow_result["parent_job"]["job_id"], "Child parent ID mismatch"
        assert "task" in child_msg, "Child task data missing"
        assert "value" in child_msg, "Child value data missing"
    
    print(f"✅ Flow processing test passed")
    print(f"   Parent processed: {len(flow_parent_worker.processed_messages)} messages")
    print(f"   Children processed: {len(flow_child_worker.processed_messages)} messages")
    print(f"   Flow ID: {flow_result['flow_id']}")

def test_bullmq_flow_error_handling():
    """Test para verificar manejo de errores en la configuración del flow."""
    # Test con configuración inválida - sin nombre
    invalid_config_1 = {
        "queueName": "test_queue",
        "children": []
    }
    
    flow_result_1 = bullmq_flow(invalid_config_1)
    assert flow_result_1["status"] == "error", "Should fail without name"
    assert "name" in flow_result_1["error"], "Error message should mention missing name"
    
    # Test con configuración inválida - sin queueName
    invalid_config_2 = {
        "name": "test-job",
        "children": []
    }
    
    flow_result_2 = bullmq_flow(invalid_config_2)
    assert flow_result_2["status"] == "error", "Should fail without queueName"
    assert "queueName" in flow_result_2["error"], "Error message should mention missing queueName"
    
    # Test con configuración válida pero hijos mal configurados
    mixed_config = {
        "name": "mixed-test-job",
        "queueName": "test_mixed_parents",
        "children": [
            {
                "name": "valid-child",
                "queueName": "test_mixed_children",
                "data": {"x": 1}
            },
            {
                "name": "invalid-child",
                # Missing queueName
                "data": {"x": 2}
            }
        ]
    }
    
    flow_result_3 = bullmq_flow(mixed_config)
    assert flow_result_3["status"] == "success", "Should succeed with mixed children"
    assert flow_result_3["children_count"] == 1, "Should create only valid children"
    assert flow_result_3["children_success"] == 1, "Should report correct success count"
    
    print("✅ Error handling tests passed")

def test_bullmq_flow_multiple_queues():
    """Test de flow con hijos en diferentes colas."""
    # Configuración del flow con múltiples colas
    multi_queue_config = {
        "name": "multi-queue-parent",
        "queueName": "multi_parents",
        "data": {"type": "multi_queue_test", "test_id": "multi_queue_001"},
        "children": [
            {
                "name": "analytics-child",
                "queueName": "analytics_queue",
                "data": {"type": "analytics", "metrics": {"views": 100, "clicks": 25}},
                "opts": {"priority": 8}
            },
            {
                "name": "notification-child",
                "queueName": "notification_queue", 
                "data": {"type": "notification", "recipient": "user@example.com", "template": "welcome"},
                "opts": {"priority": 7}
            },
            {
                "name": "logging-child",
                "queueName": "logging_queue",
                "data": {"type": "logging", "event": "user_signup", "level": "info"},
                "opts": {"priority": 5}
            }
        ]
    }
    
    # Crear el flow
    flow_result = bullmq_flow(multi_queue_config)
    
    # Verificaciones
    assert flow_result["status"] == "success", f"Multi-queue flow creation failed: {flow_result}"
    assert flow_result["children_count"] == 3, "Incorrect children count"
    assert flow_result["children_success"] == 3, "Not all children created successfully"
    
    # Verificar que los hijos están en diferentes colas
    children = flow_result["children"]
    queues = [child["child_queue"] for child in children]
    expected_queues = ["analytics_queue", "notification_queue", "logging_queue"]
    
    assert all(queue in expected_queues for queue in queues), "Children not in expected queues"
    assert len(set(queues)) == 3, "Children should be in different queues"
    
    # Verificar metadata específica
    analytics_child = next(c for c in children if c["child_name"] == "analytics-child")
    notification_child = next(c for c in children if c["child_name"] == "notification-child")
    logging_child = next(c for c in children if c["child_name"] == "logging-child")
    
    assert analytics_child["child_queue"] == "analytics_queue", "Analytics child queue incorrect"
    assert notification_child["child_queue"] == "notification_queue", "Notification child queue incorrect"
    assert logging_child["child_queue"] == "logging_queue", "Logging child queue incorrect"
    
    print(f"✅ Multi-queue flow created successfully: {flow_result['flow_id']}")
    print(f"   Children distributed across {len(set(queues))} different queues")
    for child in children:
        print(f"   - {child['child_name']}: {child['child_job_id']} in {child['child_queue']}")

def test_bullmq_flow_async_version():
    """Test de la versión asíncrona de bullmq_flow."""
    
    async def async_flow_test():
        flow_config = {
            "name": "async-test-parent",
            "queueName": "async_parents",
            "data": {"async_test": True, "timestamp": datetime.now().isoformat()},
            "children": [
                {
                    "name": "async-child-1",
                    "queueName": "async_children",
                    "data": {"async_data": "child1_data"},
                    "opts": {"priority": 7}
                }
            ]
        }
        
        # Usar la versión asíncrona
        flow_result = await bullmq_flow_async(flow_config)
        
        # Verificaciones
        assert flow_result["status"] == "success", f"Async flow creation failed: {flow_result}"
        assert "flow_id" in flow_result, "Flow ID missing"
        assert flow_result["children_count"] == 1, "Incorrect children count"
        
        return flow_result
    
    # Ejecutar el test asíncrono
    flow_result = asyncio.run(async_flow_test())
    
    print(f"✅ Async flow test passed: {flow_result['flow_id']}")

def test_bullmq_flow_dashboard_manual_execution():
    """Test para verificar compatibilidad con ejecución manual desde dashboard."""
    print("🎯 DASHBOARD MANUAL EXECUTION COMPATIBILITY TEST")
    print("=" * 60)
    
    # Configuración del flow con nombres explícitos para testing manual
    manual_flow_config = {
        "name": "manual-execution-parent",
        "queueName": "manual_test_parents",
        "data": {
            "message": "This job can be executed manually from dashboard",
            "instructions": "Copy this data to create manual jobs",
            "test_type": "manual_execution"
        },
        "opts": {
            "priority": 7,
            "jobId": "MANUAL_PARENT_001"  # Nombre explícito para dashboard
        },
        "children": [
            {
                "name": "manual-child-immediate",
                "queueName": "manual_test_children",
                "data": {
                    "task": "immediate_processing",
                    "value": 100,
                    "manual_friendly": True,
                    "description": "This child executes immediately"
                },
                "opts": {
                    "priority": 8,
                    "jobId": "MANUAL_CHILD_IMMEDIATE_001"
                }
            },
            {
                "name": "manual-child-delayed",
                "queueName": "manual_test_children",
                "data": {
                    "task": "delayed_processing", 
                    "value": 200,
                    "manual_friendly": True,
                    "description": "This child has 5 second delay"
                },
                "opts": {
                    "delay": 5000,  # 5 segundos
                    "priority": 9,
                    "jobId": "MANUAL_CHILD_DELAYED_001"
                }
            }
        ]
    }
    
    print("\\n📋 Creating flow with manual-friendly job names and data...")
    
    flow_result = bullmq_flow(manual_flow_config)
    
    assert flow_result["status"] == "success", f"Flow creation failed: {flow_result}"
    
    print(f"✅ Flow created: {flow_result['flow_id']}")
    
    # Mostrar información detallada para ejecución manual
    parent_info = flow_result["parent_job"]
    print(f"\\n📋 PARENT JOB (Queue: {parent_info['queue']}):")
    print(f"   Job Name: {parent_info.get('name', 'N/A')}")
    print(f"   Job ID: {parent_info['job_id']}")
    print(f"   Priority: {parent_info['priority']}")
    print(f"   Delay: {parent_info['delay']} seconds")
    
    print(f"\\n📋 CHILD JOBS:")
    for i, child in enumerate(flow_result['children']):
        print(f"   Child {i+1} (Queue: {child['child_queue']}):")
        print(f"     Job Name: {child['child_name']}")
        print(f"     Job ID: {child['child_job_id']}")
        print(f"     Priority: {child['child_priority']}")
        print(f"     Delay: {child['child_delay']} seconds")
    
    print(f"\\n🎯 MANUAL EXECUTION INFO FOR DASHBOARD:")
    print("=" * 60)
    print("You can now execute these jobs manually from BullMQ Dashboard:")
    print(f"\\n1. Parent Job (Queue: {parent_info['queue']}):")
    print("   Job Name: MANUAL_PARENT_001")
    print("   Job Data: {")
    print('     "message": "This job can be executed manually from dashboard",')
    print('     "instructions": "Copy this data to create manual jobs",')
    print('     "test_type": "manual_execution",')
    print(f'     "_flow_id": "{flow_result["flow_id"]}",')
    print('     "_flow_type": "parent",')
    print('     "_flow_name": "manual-execution-parent"')
    print("   }")
    print('   Job Options: { "priority": 7 }')
    
    for i, child in enumerate(flow_result['children']):
        child_config = manual_flow_config['children'][i]
        delay_info = f', "delay": {child_config["opts"].get("delay", 0)}' if child_config["opts"].get("delay") else ""
        
        print(f"\\n{i+2}. Child Job {i+1} (Queue: {child['child_queue']}):")
        print(f"   Job Name: {child_config['opts'].get('jobId', 'AUTO_GENERATED')}")
        print("   Job Data: {")
        for key, value in child_config['data'].items():
            print(f'     "{key}": "{value}",')
        print(f'     "_flow_id": "{flow_result["flow_id"]}",')
        print('     "_flow_type": "child",')
        print(f'     "_parent_job_id": "{parent_info["job_id"]}",')
        print(f'     "_child_index": {i}')
        print("   }")
        print(f'   Job Options: {{ "priority": {child["child_priority"]}{delay_info} }}')
    
    print("\\n✅ Manual execution compatibility test completed!")
    print("Copy the Job Data and Job Options above to execute manually from dashboard.")
    
    return flow_result

def test_bullmq_flow_dashboard_visibility():
    """Test específico para verificar visibilidad en el dashboard de BullMQ."""
    print("🎯 DASHBOARD VISIBILITY TEST FOR FLOWS")
    print("=" * 50)
    
    # Configuración del flow para testing de dashboard
    dashboard_flow_config = {
        "name": "dashboard-visibility-parent",
        "queueName": "dashboard_parents",
        "data": {"dashboard_test": True, "timestamp": datetime.now().isoformat()},
        "opts": {"priority": 8},
        "children": [
            {
                "name": "waiting-child",
                "queueName": "dashboard_children",
                "data": {"type": "waiting", "should_appear_in": "WAITING"},
                "opts": {"priority": 7}
            },
            {
                "name": "delayed-child", 
                "queueName": "dashboard_children",
                "data": {"type": "delayed", "should_appear_in": "DELAYED"},
                "opts": {
                    "delay": 15000,  # 15 segundos delay
                    "priority": 9
                }
            },
            {
                "name": "high-priority-child",
                "queueName": "dashboard_children",
                "data": {"type": "priority", "should_appear_in": "PRIORITIZED"},
                "opts": {"priority": 10}
            }
        ]
    }
    
    print("\n📋 PASO 1: Creando flow SIN consumers activos...")
    
    # Crear flow sin consumers para ver en dashboard
    flow_result = bullmq_flow(dashboard_flow_config)
    
    assert flow_result["status"] == "success", f"Flow creation failed: {flow_result}"
    
    print(f"✅ Flow created: {flow_result['flow_id']}")
    print(f"   Parent: {flow_result['parent_job']['job_id']} in queue '{flow_result['parent_job']['queue']}'")
    
    for i, child in enumerate(flow_result['children']):
        print(f"   Child {i+1}: {child['child_job_id']} in queue '{child['child_queue']}' (delay: {child['child_delay']}s, priority: {child['child_priority']})")
    
    print("\n🔍 VERIFICA EN EL DASHBOARD DE BULLMQ:")
    print("- Queue 'dashboard_parents': Debería mostrar 1 job WAITING")
    print("- Queue 'dashboard_children': Debería mostrar:")
    print("  * WAITING: waiting-child (priority 7)")
    print("  * PRIORITIZED: high-priority-child (priority 10)")  
    print("  * DELAYED: delayed-child (15s delay, priority 9)")
    
    print("\nEspera 10 segundos para revisar el dashboard...")
    time.sleep(10)
    
    print("\n📋 PASO 2: Activando consumers para procesar...")
    
    # Limpiar mensajes previos
    flow_parent_worker.processed_messages = []
    flow_child_worker.processed_messages = []
    
    def run_dashboard_parent_consumer():
        try:
            consumer_bullmq(worker="dashboard_parents", function_process=flow_parent_worker)
        except KeyboardInterrupt:
            pass
    
    def run_dashboard_child_consumer():
        try:
            consumer_bullmq(worker="dashboard_children", function_process=flow_child_worker)
        except KeyboardInterrupt:
            pass
    
    # Iniciar consumers
    parent_thread = threading.Thread(target=run_dashboard_parent_consumer)
    parent_thread.daemon = True
    parent_thread.start()
    
    child_thread = threading.Thread(target=run_dashboard_child_consumer)
    child_thread.daemon = True
    child_thread.start()
    
    print("Consumers activados - procesando jobs inmediatos...")
    time.sleep(5)
    
    print("\n🔍 VERIFICA EN EL DASHBOARD DE BULLMQ:")
    print("- ACTIVE: Posiblemente showing jobs being processed")
    print("- COMPLETED: Jobs that finished processing (with logs)")
    print("- DELAYED: delayed-child still waiting for its 15s delay")
    
    # Verificar que algunos jobs fueron procesados
    total_processed = len(flow_parent_worker.processed_messages) + len(flow_child_worker.processed_messages)
    
    print(f"\n📊 RESULTADOS:")
    print(f"   Jobs procesados: {total_processed}")
    print(f"   Parent procesados: {len(flow_parent_worker.processed_messages)}")
    print(f"   Children procesados: {len(flow_child_worker.processed_messages)}")
    
    if total_processed > 0:
        print("✅ Jobs están siendo procesados - revisa el dashboard para logs detallados")
        # Mostrar un ejemplo de mensaje procesado
        if flow_parent_worker.processed_messages:
            example_parent = flow_parent_worker.processed_messages[0]
            print(f"   Ejemplo parent: flow_id={example_parent.get('_flow_id', 'N/A')}, type={example_parent.get('_flow_type', 'N/A')}")
        
        if flow_child_worker.processed_messages:
            example_child = flow_child_worker.processed_messages[0]
            print(f"   Ejemplo child: parent_id={example_child.get('_parent_job_id', 'N/A')}, type={example_child.get('type', 'N/A')}")
    
    print(f"\n🎯 DASHBOARD VISIBILITY TEST COMPLETED!")
    return flow_result

def test_bullmq_flow_status():
    """Test básico para verificar el status de un flow."""
    # Crear un flow primero
    flow_config = {
        "name": "status-test-parent",
        "queueName": "status_parents",
        "children": [
            {
                "name": "status-child",
                "queueName": "status_children",
                "data": {"x": 1}
            }
        ]
    }
    
    flow_result = bullmq_flow(flow_config)
    assert flow_result["status"] == "success", "Flow creation should succeed"
    
    # Verificar status del flow
    flow_id = flow_result["flow_id"]
    status_result = bullmq_flow_status(flow_id)
    
    # Por ahora, la función de status retorna "not_implemented"
    assert "status" in status_result, "Status result should have status field"
    assert status_result["flow_id"] == flow_id, "Flow ID should match"
    
    print(f"✅ Flow status test completed: {status_result['status']}")

# Función de limpieza para los tests
def cleanup_flow_test_queues():
    """Limpia las colas de test después de ejecutar los tests."""
    from .bullmq_delete_all_job import bullmq_delete_all_job
    
    test_queues = [
        "test_parents", "test_children",
        "test_delay_parents", "test_delay_children",
        "processing_parents", "processing_children",
        "test_mixed_parents", "test_mixed_children",
        "multi_parents", "analytics_queue", "notification_queue", "logging_queue",
        "async_parents", "async_children",
        "status_parents", "status_children",
        "dashboard_parents", "dashboard_children",
        "manual_test_parents", "manual_test_children"
    ]
    
    for queue_name in test_queues:
        try:
            result = bullmq_delete_all_job(queue_name)
            if result["total"] > 0:
                print(f"Cleaned {result['total']} jobs from queue '{queue_name}'")
        except Exception as e:
            print(f"Warning: Could not clean queue '{queue_name}': {e}")
    
    print("✅ Flow test queues cleaned")

if __name__ == "__main__":
    print("🧪 Running BullMQ Flow Tests...")
    
    try:
        test_bullmq_flow_basic()
        test_bullmq_flow_with_delays()
        test_bullmq_flow_error_handling()
        test_bullmq_flow_multiple_queues()
        test_bullmq_flow_async_version()
        test_bullmq_flow_status()
        
        # Test específico para compatibilidad con dashboard manual
        print("\n🎯 Running dashboard manual execution compatibility test...")
        test_bullmq_flow_dashboard_manual_execution()
        
        # Test específico para dashboard visibility
        print("\n🎯 Running dashboard visibility test...")
        test_bullmq_flow_dashboard_visibility()
        
        # Test de procesamiento (requiere más tiempo)
        print("\n⏱️  Running processing test (may take a few seconds)...")
        test_bullmq_flow_processing()
        
        print("\n🎉 All flow tests passed!")
        
    except Exception as e:
        print(f"❌ Test failed: {e}")
        raise
    finally:
        print("\n🧹 Cleaning up test queues...")
        cleanup_flow_test_queues()