﻿#!/usr/bin/env python3
"""
Harvestree uplink consumer — MQTT (ChirpStack v4).

Subscribe to application/*/device/*/event/up and print normalized metrics.
Use when your LNS publishes uplinks to a shared MQTT broker (multi-subscriber,
fan-out to several services).

See ../README.md for when to pick MQTT vs HTTP or Python vs Node.js.

Env:
  MQTT_HOST (default 127.0.0.1)
  MQTT_PORT (default 1883)
  MQTT_TOPIC (default application/+/device/+/event/up)
"""

from __future__ import annotations

import json
import os
import sys

try:
    import paho.mqtt.client as mqtt
except ImportError:
    print("Install dependencies: pip install -r requirements.txt", file=sys.stderr)
    raise

from ingest_common import print_batch, process_envelope


def on_message(_client, _userdata, msg) -> None:
    try:
        envelope = json.loads(msg.payload.decode("utf-8"))
    except json.JSONDecodeError as exc:
        print(f"skip invalid json: {exc}")
        return

    batch = process_envelope(envelope)
    if batch:
        print_batch(batch)


def main() -> None:
    host = os.environ.get("MQTT_HOST", "127.0.0.1")
    port = int(os.environ.get("MQTT_PORT", "1883"))
    topic = os.environ.get("MQTT_TOPIC", "application/+/device/+/event/up")

    client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
    client.on_message = on_message
    client.connect(host, port, 60)
    client.subscribe(topic)
    print(f"MQTT listening on {topic} ({host}:{port})")
    client.loop_forever()


if __name__ == "__main__":
    main()
