import json
import uuid
import pika
from pika.delivery_mode import DeliveryMode


class MQProducer:
    """RabbitMQ生产者类
    
    负责发送普通消息和延迟消息到RabbitMQ队列
    """

    def __init__(self, connection, config):
        """初始化MQProducer
        
        Args:
            connection: MQConnection对象，用于创建RabbitMQ连接
            config: MQConfig对象，包含RabbitMQ配置
        """
        self.connection = connection  # 连接对象
        self.config = config  # 配置对象
        self.channel = connection.connect()  # 创建通道
        self.delay_exchange = config.delay_exchange  # 延迟交换机名称

    def send(self, queue, message):
        """发送普通消息
        
        Args:
            queue: 队列名称
            message: 消息内容（字典）
            
        Returns:
            str: 消息ID
        """
        message_id = str(uuid.uuid4())  # 生成唯一消息ID

        # 发送消息
        self.channel.basic_publish(
            exchange="",  # 默认交换机
            routing_key=queue,  # 队列名称作为路由键
            body=json.dumps(message),  # 消息体
            properties=pika.BasicProperties(
                message_id=message_id,  # 消息ID
                delivery_mode=DeliveryMode.Persistent  # 持久化消息
            )
        )

        return message_id

    def send_delay(self, queue, message, delay_ms):
        """发送延迟消息
        
        Args:
            queue: 队列名称
            message: 消息内容（字典）
            delay_ms: 延迟时间（毫秒）
            
        Returns:
            str: 消息ID
        """
        message_id = str(uuid.uuid4())  # 生成唯一消息ID

        # 确保延迟交换机和队列之间已经绑定
        print(f"Binding queue {queue} to delay exchange {self.delay_exchange}...")
        self.channel.queue_bind(
            queue=queue,
            exchange=self.delay_exchange,
            routing_key=queue
        )
        print(f"Queue {queue} bound to delay exchange {self.delay_exchange} successfully")

        print(f"Sending delay message to queue: {queue}, message: {message}, delay: {delay_ms}ms")
        # 发送延迟消息
        self.channel.basic_publish(
            exchange=self.delay_exchange,  # 延迟交换机
            routing_key=queue,  # 队列名称作为路由键
            body=json.dumps(message),  # 消息体
            properties=pika.BasicProperties(
                headers={"x-delay": delay_ms},  # 延迟时间
                message_id=message_id,  # 消息ID
                delivery_mode=DeliveryMode.Persistent  # 持久化消息
            )
        )
        print(f"Delay message sent successfully with ID: {message_id}")

        return message_id