"""
Temps dashboard: Flask backend for MySQL shop_stats.Temps.
Serves latest record per unit_id (by entry_date) as JSON and a single-page UI.
"""
import os
import pymysql
from flask import Flask, render_template, jsonify

app = Flask(__name__)

# MySQL config from environment (Temps connection defaults)
def _get_config():
    return {
        "host": os.environ.get("TEMPS_MYSQL_HOST", "192.168.50.5"),
        "port": int(os.environ.get("TEMPS_MYSQL_PORT", "3306")),
        "database": os.environ.get("TEMPS_MYSQL_DATABASE", "shop_stats"),
        "user": os.environ.get("TEMPS_MYSQL_USER", "bill"),
        "password": os.environ.get("TEMPS_MYSQL_PASSWORD", "5074367"),
    }


def get_latest_per_unit():
    """Return list of latest Temps row per unit_id (by entry_date)."""
    cfg = _get_config()
    if not cfg["password"]:
        return None, "TEMPS_MYSQL_PASSWORD is not set"
    try:
        conn = pymysql.connect(
            host=cfg["host"],
            port=cfg["port"],
            user=cfg["user"],
            password=cfg["password"],
            database=cfg["database"],
            cursorclass=pymysql.cursors.DictCursor,
        )
    except pymysql.Error as e:
        return None, str(e)
    query = """
        SELECT t.unit_id, t.node_name, t.temp, t.humid, t.bat
        FROM Temps t
        INNER JOIN (
            SELECT unit_id, MAX(entry_date) AS max_entry_date
            FROM Temps
            WHERE entry_date >= NOW() - INTERVAL 10 MINUTE
            GROUP BY unit_id
        ) latest ON t.unit_id = latest.unit_id AND t.entry_date = latest.max_entry_date
        WHERE t.entry_date >= NOW() - INTERVAL 10 MINUTE
        ORDER BY t.unit_id
    """
    try:
        with conn.cursor() as cur:
            cur.execute(query)
            rows = cur.fetchall()
    finally:
        conn.close()
    return rows, None


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/api/latest")
def api_latest():
    rows, err = get_latest_per_unit()
    if err:
        return jsonify({"error": err}), 500
    return jsonify(rows)


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)
