import asyncio
import redis.asyncio as redis
import json
import logging
import anyio

# Mock some things for the local test
class MockWebSocket:
    def __init__(self):
        self.sent_messages = []
        self.is_open = True
    async def send_text(self, text):
        if not self.is_open:
            raise Exception("Closed")
        self.sent_messages.append(text)
        print(f"WS Sent: {text}")

# Import the logic we want to test
from app.api.websocket import ConnectionManager
from app.services.infra.redis import publish_event

async def test_reconnection():
    manager = ConnectionManager()
    ws = MockWebSocket()
    channel = "test_channel"
    
    print("Starting listener...")
    task = asyncio.create_task(manager._listen_to_redis(ws, channel))
    
    await asyncio.sleep(1)
    
    print("Publishing message 1...")
    await publish_event(channel, {"msg": "hello 1"})
    
    await asyncio.sleep(1)
    
    # We can't easily "kill" redis here without affecting the whole test
    # but we can verify that the listener works and sends the message.
    
    if len(ws.sent_messages) > 0:
        print("SUCCESS: Message received.")
    else:
        print("FAILURE: Message not received.")
        
    task.cancel()
    await asyncio.gather(task, return_exceptions=True)

if __name__ == "__main__":
    asyncio.run(test_reconnection())
