# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
# ---- Example 2: the history of YOUR devices, as stored by Telegraf
# pivot() turns the three field rows of each moment into one row with three columns.

import os
from statistics import mean

from influxdb_client import InfluxDBClient

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")
STUDENT_ID = os.getenv("STUDENT_ID", "lab-local")

FLUX = f'''from(bucket: "{BUCKET}")
  |> range(start: -1h)
  |> filter(fn: (r) => r._measurement == "environment" and r.student == "{STUDENT_ID}")
  |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value")'''


def main() -> None:
    with InfluxDBClient(url=URL, token=TOKEN, org=ORG) as client:
        tables = client.query_api().query(FLUX, org=ORG)

    rows = [rec.values for table in tables for rec in table.records]   # one dict per moment
    if not rows:
        raise SystemExit(f"No data for student {STUDENT_ID}: is Telegraf running and your device publishing?")

    print(f"History of student {STUDENT_ID}, last hour")
    print(f"{'node':<12}{'readings':>9}{'T min':>8}{'T mean':>8}{'T max':>8}{'last soil':>11}")
    for node in sorted({r['node'] for r in rows}):
        mine = sorted((r for r in rows if r['node'] == node), key=lambda r: r['_time'])
        temps = [r['temperature'] for r in mine]
        print(f"{node:<12}{len(mine):>9}{min(temps):>8.1f}{mean(temps):>8.2f}{max(temps):>8.1f}"
              f"{mine[-1]['soil_moisture']:>11.1f}")


if __name__ == "__main__":
    main()
