import logging
import threading
from connection import MQConnection
from consumer import MQConsumer
from decorator import _listener_registry

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s')

class MQStarter:
    """RabbitMQ启动器类
    
    负责初始化RabbitMQ交换机和启动消费者
    """

    def __init__(self, config):
        """初始化MQStarter
        
        Args:
            config: MQConfig对象，包含RabbitMQ配置
        """
        self.connection = MQConnection(config)  # 连接对象
        self.config = config  # 配置对象

    def start(self):
        """启动RabbitMQ服务
        
        初始化交换机并启动消费者线程
        """

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

            Args:
                queue: 队列名称
                handler: 消息处理函数
            """
            while True:
                try:
                    consumer = MQConsumer(self.config)
                    consumer.listen(queue, 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)

        threads = []

        # 为每个注册的队列启动一个消费者线程
        for queue, handler in _listener_registry:
            t = threading.Thread(
                target=start_consumer,
                args=(queue, handler)
            )
            t.daemon = True  # 守护线程
            t.start()
            threads.append(t)

        # 主线程保持运行，支持 Ctrl+C 优雅退出
        try:
            while True:
                import time
                time.sleep(1)
        except KeyboardInterrupt:
            logging.error("MQStarter stopped by user")