# -*- coding: utf-8 -*-
import pika
import sys

# 连接参数
user_info = pika.PlainCredentials('user', 'J70e6K7BRrxrU1dO')
connection = pika.BlockingConnection(
    pika.ConnectionParameters('rabbitmq.rabbitmq.svc.cluster.local',
                              5672,
                              '/',
                              user_info)
)
channel = connection.channel()

# 1. 声明同一个 direct 交换机
channel.exchange_declare(exchange='direct_logs', exchange_type='direct')

# 2. 创建临时队列
result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue

# 3. 从命令行读取要绑定的 routing_key，可多个
severities = sys.argv[1:]
if not severities:
    sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
    sys.exit(1)

for severity in severities:
    channel.queue_bind(exchange='direct_logs', queue=queue_name, routing_key=severity)

print(' [*] Waiting for logs. To exit press CTRL+C')

# 4. 回调
def callback(ch, method, properties, body):
    print(f" [x] {method.routing_key}:{body.decode()}")

channel.basic_consume(
    queue=queue_name,
    on_message_callback=callback,
    auto_ack=True
)

channel.start_consuming()