import logging
import threading
import time

from .consumer import MQConsumer
from .config import MQConfig

_listener_registry = []  # 监听器注册表


def mq_listener(queue, prefetch=10, workers=5):
    """消息监听器装饰器
    
    用于注册消息处理函数到指定的队列
    
    Args:
        queue: 队列名称
        
    Returns:
        function: 装饰器函数
        :param queue: 队列名称
        :param workers: 消费者线程池大小
        :param prefetch: 每个消费者的预取数量
    """

    def wrapper(func):
        """装饰器包装函数
        
        Args:
            func: 消息处理函数
            
        Returns:
            function: 原函数
        """

        def start_consumer(queue, prefetch, workers, handler):
            """启动消费者线程

            Args:
                queue:
                handler:
                :param queue: 队列名称
                :param handler: 消息处理函数
                :param workers: 消费线程数
                :param prefetch: 每次取到本地消息数量
            """
            try:
                config = MQConfig()
                consumer = MQConsumer(config)
                consumer.listen(queue, prefetch, workers, handler)
            except Exception as e:
                logging.error(f"Consumer thread for queue {queue} crashed: {e}")
                logging.error(f"Restarting consumer thread for queue {queue}...")
                time.sleep(5)

        # 将队列和处理函数添加到注册表
        t = threading.Thread(
            target=start_consumer,
            args=(queue, prefetch, workers, func)
        )
        t.daemon = True  # 守护线程
        t.start()

        _listener_registry.append((queue, prefetch, workers, func))
        return func

    return wrapper
