# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Example 2: greenhouse controller — query InfluxDB, decide, drive GPIO, log
# Reads the data that Example 1 stored, asks InfluxDB questions in Flux,
# switches a fan (GPIO17) and a water pump (GPIO27) with hysteresis rules,
# and writes every decision back to InfluxDB as an "actuator" point.
# The GPIO is the mock from Lab 41, so it runs in Google Colab too.

import os
from datetime import datetime, timezone

from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS


# ---- Connection settings (same as the sensor node)
URL = os.getenv("INFLUX_URL", "http://localhost:8086")
TOKEN = os.environ["INFLUX_TOKEN"]
ORG = os.getenv("INFLUX_ORG", "psut")
BUCKET = os.getenv("INFLUX_BUCKET", "greenhouse")
SITE, NODE = "psut-greenhouse", "pi-01"

# ---- Control rules with hysteresis: two thresholds, so the relay does not chatter
FAN_ON_ABOVE, FAN_OFF_BELOW = 30.0, 28.0        # °C, mean of the last 10 readings
PUMP_ON_BELOW, PUMP_OFF_ABOVE = 35.0, 45.0      # % soil moisture, latest reading
SMOOTHING = 10                                  # readings averaged for the fan rule


# ---- Mock RPi.GPIO and the LED class from Lab 41 (an LED stands in for each relay)
class MockGPIO:
    """Stand-in for RPi.GPIO: prints every call instead of driving hardware."""
    BCM, OUT, HIGH, LOW = 'BCM', 'OUT', True, False

    @staticmethod
    def setmode(mode):
        print(f"GPIO mode set to {mode}")

    @staticmethod
    def setup(pin, mode):
        print(f"GPIO pin {pin} set up as {mode}")

    @staticmethod
    def output(pin, state):
        print(f"GPIO pin {pin} set to {'HIGH' if state else 'LOW'}")

    @staticmethod
    def cleanup():
        print("GPIO cleanup")


GPIO = MockGPIO                                 # on a real Pi: import RPi.GPIO as GPIO


class LED:
    """One output on one GPIO pin (here: the indicator LED of a relay)."""

    def __init__(self, pin: int) -> None:
        self.pin = pin
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.pin, GPIO.OUT)
        self.state = GPIO.LOW
        GPIO.output(self.pin, self.state)       # start OFF

    def turn_on(self) -> None:
        self.state = GPIO.HIGH
        GPIO.output(self.pin, self.state)

    def turn_off(self) -> None:
        self.state = GPIO.LOW
        GPIO.output(self.pin, self.state)

    @staticmethod
    def check_pin_availability(pin: int) -> bool:
        return 1 <= pin <= 40

    @classmethod
    def create_led(cls, pin: int) -> 'LED':
        if cls.check_pin_availability(pin):
            return cls(pin)
        raise ValueError("GPIO pin is not available")

    def cleanup(self) -> None:
        GPIO.cleanup()


# ---- Flux queries: each one is a pipeline of functions joined by |>
def flux_latest(field: str) -> str:
    """The newest value of one field."""
    return f'''from(bucket: "{BUCKET}")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "environment" and r._field == "{field}")
  |> filter(fn: (r) => r.node == "{NODE}")
  |> last()'''


def flux_recent_mean(field: str, n: int) -> str:
    """The mean of the newest n values of one field (smooths sensor noise)."""
    return f'''from(bucket: "{BUCKET}")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "environment" and r._field == "{field}")
  |> filter(fn: (r) => r.node == "{NODE}")
  |> tail(n: {n})
  |> mean()'''


def flux_windows(field: str) -> str:
    """One mean per 5-minute window (what a dashboard graph shows)."""
    return f'''from(bucket: "{BUCKET}")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "environment" and r._field == "{field}")
  |> filter(fn: (r) => r.node == "{NODE}")
  |> aggregateWindow(every: 5m, fn: mean, createEmpty: false)'''


def flux_actuator_state() -> str:
    """The last logged state of every actuator (one table per device tag)."""
    return f'''from(bucket: "{BUCKET}")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "actuator" and r._field == "state")
  |> filter(fn: (r) => r.node == "{NODE}")
  |> last()'''


def first_value(query_api, flux: str):
    """Run a query and return the first value, or None if there is no data."""
    tables = query_api.query(flux, org=ORG)
    if not tables or not tables[0].records:
        return None
    return tables[0].records[0].get_value()


# ---- Hysteresis: switch on above one threshold, off below another, else keep
def decide(is_on: bool, value: float, on_when, off_when) -> bool:
    if not is_on and on_when(value):
        return True
    if is_on and off_when(value):
        return False
    return is_on


# ---- Main program
def main() -> None:
    fan = pump = None
    try:
        with InfluxDBClient(url=URL, token=TOKEN, org=ORG) as client:
            query_api = client.query_api()
            write_api = client.write_api(write_options=SYNCHRONOUS)

            # ---- 1. What is happening now?
            t = first_value(query_api, flux_latest("temperature"))
            h = first_value(query_api, flux_latest("humidity"))
            s = first_value(query_api, flux_latest("soil_moisture"))
            if t is None:
                raise SystemExit("No data yet: run Example 1 (greenhouse_node.py) first.")
            print(f"Latest reading: T={t:.1f} °C  RH={h:.1f} %  soil={s:.1f} %")

            # ---- 2. The trend: one mean per 5-minute window, oldest first
            records = query_api.query(flux_windows("temperature"), org=ORG)[0].records
            print("Temperature, 5-minute means (oldest first):")
            for number, rec in enumerate(records, start=1):
                print(f"  window {number}  {rec.get_value():5.2f} °C")   # rec.get_time() = window end

            # ---- 3. Smoothed value for the fan rule
            t_mean = first_value(query_api, flux_recent_mean("temperature", SMOOTHING))
            print(f"Mean of the last {SMOOTHING} temperatures: {t_mean:.2f} °C")

            # ---- 4. Previous actuator states are stored in InfluxDB too (OFF if none yet)
            previous = {"fan": False, "pump": False}
            for table in query_api.query(flux_actuator_state(), org=ORG):
                for rec in table.records:
                    previous[rec.values["device"]] = rec.get_value() == 1

            # ---- 5. Decide with hysteresis
            fan_on = decide(previous["fan"], t_mean,
                            lambda v: v > FAN_ON_ABOVE, lambda v: v < FAN_OFF_BELOW)
            pump_on = decide(previous["pump"], s,
                             lambda v: v < PUMP_ON_BELOW, lambda v: v > PUMP_OFF_ABOVE)

            # ---- 6. Act: drive the GPIO pins (fan relay GPIO17, pump relay GPIO27)
            fan = LED.create_led(17)
            pump = LED.create_led(27)
            fan.turn_on() if fan_on else fan.turn_off()
            pump.turn_on() if pump_on else pump.turn_off()
            print(f"Fan  {'ON ' if fan_on else 'OFF'}  (mean {t_mean:.2f} °C, on above {FAN_ON_ABOVE}, off below {FAN_OFF_BELOW})")
            print(f"Pump {'ON ' if pump_on else 'OFF'}  (soil {s:.1f} %, on below {PUMP_ON_BELOW}, off above {PUMP_OFF_ABOVE})")

            # ---- 7. Log the decisions: actuator points, state as an integer 0/1
            now = datetime.now(timezone.utc)
            reasons = {"fan": f"mean {t_mean:.2f} C", "pump": f"soil {s:.1f} %"}
            events = [
                Point("actuator").tag("site", SITE).tag("node", NODE).tag("device", device)
                .field("state", int(on)).field("reason", reasons[device]).time(now)
                for device, on in (("fan", fan_on), ("pump", pump_on))
            ]
            write_api.write(bucket=BUCKET, org=ORG, record=events)
            print(f"Logged {len(events)} actuator events")

            # ---- 8. Read them back: the database now holds the control history
            stored = {t.records[0].values["device"]: t.records[0].get_value()
                      for t in query_api.query(flux_actuator_state(), org=ORG)}
            for device in sorted(stored):
                print(f"  stored: {device:<4} state={stored[device]}")
    finally:
        if fan is not None:                     # release the pins whatever happened
            fan.cleanup()


if __name__ == "__main__":
    main()
