#!/bin/bash
# weather_02532_sun.sh
# Bourne, MA (02532) external heating drivers:
# - OpenWeatherMap "now"
# - simple sun azimuth + daylight + solar window + cloud factor
# Runs forever, append-only CSV.

API_KEY="3d81390cf5254bb05d7ec2687262007d"
CITY="Bourne,us"
OUT="02532.csv"

# Header once
if [ ! -f "$OUT" ]; then
  echo "timestamp_iso,epoch,lat,lon,temp_k,feels_like_k,humidity_pct,pressure_hpa,wind_mps,wind_gust_mps,wind_deg,clouds_pct,weather,sun_az_deg,daylight,solar_window,cloud_factor" > "$OUT"
fi

while true; do
  TS_ISO=$(date -Is)
  TS_EPOCH=$(date +%s)

  # --- Simple sun model (no API):
  # Approx azimuth from 90° at midnight to 270° at end of day.
  # Good enough to correlate “morning vs afternoon solar gain”.
  SECONDS_TODAY=$(( $(date +%s) - $(date -d "$(date +%F) 00:00:00" +%s) ))
  SUN_AZ=$(awk "BEGIN { printf \"%.2f\", 90 + 180*($SECONDS_TODAY/86400) }")

  # Daylight if sun azimuth between 90 and 270 (crude, but useful)
  DAYLIGHT=$(awk "BEGIN {print ($SUN_AZ>=90 && $SUN_AZ<=270) ? 1 : 0}")

  # “Solar window” if sun is in the southern half-ish (120..240)
  SOLAR_WINDOW=$(awk "BEGIN {print ($SUN_AZ>120 && $SUN_AZ<240) ? 1 : 0}")

  # --- Fetch OpenWeather "now"
  JSON=$(curl -s "https://api.openweathermap.org/data/2.5/weather?q=${CITY}&APPID=${API_KEY}")

  # Cloud factor: 1.00 clear, 0.00 fully overcast
  CLOUDS=$(echo "$JSON" | jq -r '.clouds.all // ""')
  CLOUD_FACTOR=$(awk -v c="$CLOUDS" 'BEGIN { if (c=="") print ""; else printf "%.3f", (1 - c/100.0) }')

  echo "$JSON" | jq -r \
    --arg iso "$TS_ISO" \
    --arg ep "$TS_EPOCH" \
    --arg sunaz "$SUN_AZ" \
    --arg daylight "$DAYLIGHT" \
    --arg solarwin "$SOLAR_WINDOW" \
    --arg cloudf "$CLOUD_FACTOR" \
    '
    [
      $iso,
      $ep,
      .coord.lat,
      .coord.lon,
      .main.temp,
      .main.feels_like,
      .main.humidity,
      .main.pressure,
      .wind.speed,
      (.wind.gust // ""),
      .wind.deg,
      .clouds.all,
      .weather[0].description,
      $sunaz,
      $daylight,
      $solarwin,
      $cloudf
    ] | @csv
    ' >> "$OUT"

  sleep 1200   # 20 minutes
done
