#!/usr/bin/env python3
"""
Optional Home Assistant / Raspberry Pi Supervisor Polling Script
================================================================
Polls http://heliostat.local/api/status on your local LAN, logs exterior wall
heat-exchange temperatures (F) and heliostat angles, and triggers thermal defocus
if indoor room thermostats have already reached comfort setpoint.
"""

import json
import time
import urllib.request

HELIOSTAT_HOST = "http://heliostat.local"
MAX_INDOOR_ROOM_TEMP_F = 73.5


def fetch_status() -> dict:
    with urllib.request.urlopen(f"{HELIOSTAT_HOST}/api/status", timeout=5) as resp:
        return json.loads(resp.read().decode("utf-8"))


def send_command(cmd: str) -> None:
    req = urllib.request.Request(f"{HELIOSTAT_HOST}/api/cmd?c={cmd}", method="POST")
    urllib.request.urlopen(req, timeout=5).read()


if __name__ == "__main__":
    print("Monitoring NightHawk Solar Thermal Heliostat at", HELIOSTAT_HOST)
    while True:
        try:
            st = fetch_status()
            print(
                f"[Heliostat] Mode={st['mode']} | Pose=({st['az']:.1f}, {st['el']:.1f} deg) | "
                f"Wall={st['wall_f']:.1f} F | Wind={st['wind_mph']:.1f} mph"
            )
        except Exception as exc:
            print("[Warn] Poll retry:", exc)
        time.sleep(10)
