import asyncio
import time
from .bullmq_sender import bullmq_sender
from .bullmq_cancel_execution import bullmq_cancel_execution
from bullmq import Queue

def debug_cancel_test():
    """Test de debugging para entender por qué falla la cancelación."""
    
    print("=== Debug Cancel Test ===")
    
    queue_name = "debug_cancel_test"
    redis_url = "redis://192.168.1.163:6379"
    
    # 1. Crear trabajo con delay
    print("1. Creating delayed job...")
    job_id = bullmq_sender(
        worker=queue_name,
        priority=5,
        delay_sec=15,
        message={"debug": True, "test": "cancellation"},
        job_id="debug_cancel_job_001"
    )
    
    print(f"Job created with ID: {job_id}")
    
    # 2. Verificar que el job existe en la cola
    print("2. Checking if job exists in queue...")
    
    async def check_job_exists():
        try:
            queue = Queue(queue_name, {"connection": redis_url})
            
            # Intentar obtener el job
            job = await queue.getJob(job_id)
            
            if job:
                print(f"✅ Job found: {job.id}")
                job_state = await job.getState()
                print(f"Job state: {job_state}")
                job_data = job.data
                print(f"Job data: {job_data}")
                
                # Listar todos los jobs en la cola
                waiting_jobs = await queue.getJobs(["waiting"], 0, 10)
                delayed_jobs = await queue.getJobs(["delayed"], 0, 10)
                
                print(f"Waiting jobs: {len(waiting_jobs)}")
                print(f"Delayed jobs: {len(delayed_jobs)}")
                
                for i, w_job in enumerate(waiting_jobs):
                    print(f"  Waiting job {i}: {w_job.id}")
                
                for i, d_job in enumerate(delayed_jobs):
                    print(f"  Delayed job {i}: {d_job.id}")
                
            else:
                print(f"❌ Job {job_id} not found in queue")
                
                # Listar todos los jobs para ver qué hay
                waiting_jobs = await queue.getJobs(["waiting"], 0, 10)
                delayed_jobs = await queue.getJobs(["delayed"], 0, 10)
                
                print(f"All waiting jobs in queue: {len(waiting_jobs)}")
                print(f"All delayed jobs in queue: {len(delayed_jobs)}")
                
                for i, job in enumerate(waiting_jobs + delayed_jobs):
                    print(f"  Job {i}: ID={job.id}, State={await job.getState()}")
                    
            await queue.close()
            return job is not None
            
        except Exception as e:
            print(f"Error checking job: {e}")
            return False
    
    time.sleep(1)  # Esperar que el job se registre
    job_exists = asyncio.run(check_job_exists())
    
    # 3. Intentar cancelar
    print("3. Attempting cancellation...")
    cancel_result = bullmq_cancel_execution(job_id, queue_name, redis_url)
    
    print(f"Cancellation result: {cancel_result}")
    
    return {
        "job_created": job_id is not None,
        "job_exists": job_exists,
        "cancel_result": cancel_result
    }

if __name__ == "__main__":
    result = debug_cancel_test()
    print(f"Final result: {result}")