# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Example 1b: a Python stand-in for the ESP32 greenhouse node
# Publishes the same JSON as the ESP32 sketch to the same topic, so you can test
# Telegraf + InfluxDB without Wokwi (for example in Google Colab).
# Needs:  pip install paho-mqtt

import json
import math
import os
import time
import threading
import re

import paho.mqtt.client as mqtt

BROKER = os.getenv("MQTT_BROKER", "127.0.0.1")   # local WSL Mosquitto
PORT = int(os.getenv("MQTT_PORT", "1884"))
STUDENT_ID = os.getenv("STUDENT_ID", "lab-local")  # topic label, not authentication
NODE = os.getenv("NODE", "python-sim")             # which device this is
TOPIC = f"psut/iot/{STUDENT_ID}/greenhouse/{NODE}/telemetry"
MESSAGES = int(os.getenv("MESSAGES", "30"))       # how many readings to send
PERIOD = float(os.getenv("PERIOD", "0.5"))        # seconds between readings


# ---- The same simulated sensors as Lab 42 (identical numbers every run)
def reading(i: int) -> dict:
    return {
        "source": "mock",
        "temperature": round(24.0 + 0.3 * i + 0.4 * math.sin(1.3 * i), 1),
        "humidity": round(max(0,min(100,72.0 - 0.6 * i + 1.2 * math.sin(0.7 * i))), 1),
        "soil_moisture": round(max(0,min(100,60.0 - 1.0 * i + 0.8 * math.sin(0.9 * i))), 1),
    }


def main() -> None:
    if MESSAGES < 1 or PERIOD <= 0: raise ValueError("MESSAGES and PERIOD must be positive")
    if BROKER.lower() == "broker.hivemq.com" and not re.fullmatch(r"demo-[0-9a-f]{16}", STUDENT_ID):
        raise SystemExit("Run tools/mqtt_profile.py hive and source the generated profile first")
    client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
    ready = threading.Event()
    def connected(c,u,f,reason,p):
        if not reason.is_failure: ready.set()
    client.on_connect = connected
    client.connect(BROKER, PORT, keepalive=30)
    client.loop_start()
    try:
        if not ready.wait(10): raise RuntimeError("MQTT CONNACK timeout")
        for i in range(MESSAGES):
            payload = json.dumps(reading(i), allow_nan=False)
            info = client.publish(TOPIC, payload, qos=1, retain=False)
            info.wait_for_publish(timeout=10)
            if not info.is_published(): raise RuntimeError("MQTT PUBACK timeout")
            print(f"{TOPIC} {payload}", flush=True)
            if i+1 < MESSAGES: time.sleep(PERIOD)
    finally:
        client.disconnect(); client.loop_stop()

if __name__ == "__main__":
    main()
