#!/usr/bin/env python3
import os
import sys
import time
import paho.mqtt.client as mqtt

broker = os.getenv('MQTT_BROKER', 'localhost:1883')
topic = os.getenv('MQTT_TOPIC', 'lambdaiot')
username = os.getenv('MQTT_USERNAME')
password = os.getenv('MQTT_PASSWORD')

if broker.startswith('tcp://'):
    broker = broker[len('tcp://'):]

host, sep, port = broker.partition(':')
port = int(port) if sep else 1883

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    client.subscribe(topic)
    print(f"Subscribed to {topic}")

def on_message(client, userdata, msg):
    try:
        payload = msg.payload.decode()
    except Exception:
        payload = str(msg.payload)
    print(f"[{msg.topic}] {payload}")

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
if username:
    client.username_pw_set(username, password)
    client.client_id = f"subscribe-{os.getpid()}"

try:
    client.connect(host, port, 60)
except Exception as e:
    print("Could not connect to broker:", e)
    sys.exit(1)

client.loop_forever()
