"""Small CPython MQTT example.

Listens and prints all received messages on the subscribed channel continuously.
Set MQTT_BROKER_HOST to the broker IP address, not localhost.
"""

import os
import time
from pathlib import Path

from shared.mqtt import BrokerClient


BROKER_HOST = os.getenv("MQTT_BROKER_HOST", "192.168.50.1")
TOPIC = "smartwave/demo"
USE_TLS = os.getenv("MQTT_CLIENT_TLS", "true").lower() in {"1", "true", "yes", "on"}
CA_FILE = os.getenv(
    "MQTT_CA_FILE",
    str(Path(__file__).resolve().parents[2] / "orchestrateur" / "mqtt" / "certs" / "ca.crt"),
)


def main():
    client = BrokerClient(
        host=BROKER_HOST,
        client_id="zephyrus",
        use_tls=USE_TLS,
        cafile=CA_FILE,
        keepalive=30,
    )

    print(f"Connexion au broker: {BROKER_HOST}...")
    client.connect()
    
    print(f"Souscription au topic: {TOPIC}...")
    client.subscribe(TOPIC, qos=2)

    print("En attente de messages... (Appuyez sur Ctrl+C pour quitter)")
    
    try:
        while True:
            # Traite le réseau et récupère les paquets MQTT entrants
            client.poll(0.1)
            
            # Récupère le message dans la file d'attente de la librairie
            message = client.get_message()
            if message is not None:
                # Décodage du payload pour un affichage plus propre en texte
                try:
                    payload_str = message['payload'].decode('utf-8')
                except Exception:
                    payload_str = message['payload']
                
                print(f"[{message['topic']}] reçu : {payload_str}")
                
    except KeyboardInterrupt:
        print("\nArrêt utilisateur")
    finally:
        client.close()
        print("Connexion MQTT fermée.")


if __name__ == "__main__":
    main()