#!/bin/bash
# weather-tag.sh — print a one-word weather tag for the current moment at
# (LATITUDE, LONGITUDE), using the OpenWeather "Current weather" endpoint.
#
# Output: a single lowercase word from this fixed vocabulary, or empty:
#     thunderstorm  rain  rainstorm  snow  snowstorm
#
# Only conditions that change the audio character get a tag.  Cloud, fog,
# clear, and wind sound essentially the same on the recordings, so they fall
# through to the un-tagged filename.
#
# Used by ambient-record.sh to suffix each 30-minute chunk's filename so the
# file collection self-documents what the audio actually captured.
#
# Failure-safe: if WEATHER_ENABLED≠true, the API key is missing, the network
# is down, the API returns an error, or the response can't be parsed, this
# script prints NOTHING and exits 0.  Callers MUST treat empty output as
# "no tag — fall back to the un-tagged filename".  Never blocks the recorder.
#
# Required setup:
#   1. Sign up at https://openweathermap.org/api → free "Current weather" plan
#   2. Put the key in .env:   OPENWEATHER_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxx
#   3. Confirm LATITUDE / LONGITUDE are set in .env (already needed by sunrise.py)
#   4. Flip WEATHER_ENABLED=true in sky-cam.conf
#
# Manual test:  ./weather-tag.sh        (prints e.g. "rain" or nothing)

set -uo pipefail   # NOT -e: we want to swallow every failure into "no tag"

SCRIPT_DIR="$(dirname "$(realpath "$0")")"
source "$SCRIPT_DIR/sky-cam.conf" 2>/dev/null || exit 0
source "$SCRIPT_DIR/.env" 2>/dev/null || true

[ "${WEATHER_ENABLED:-false}" = "true" ] || exit 0
[ -n "${OPENWEATHER_API_KEY:-}" ]        || exit 0
[ -n "${LATITUDE:-}" ]                   || exit 0
[ -n "${LONGITUDE:-}" ]                  || exit 0

# ── Fetch current conditions ─────────────────────────────────────────────────
# 5s connect / 8s total — must never delay the recorder noticeably.
url="https://api.openweathermap.org/data/2.5/weather?lat=${LATITUDE}&lon=${LONGITUDE}&appid=${OPENWEATHER_API_KEY}&units=metric"
resp=$(curl -s --connect-timeout 5 --max-time 8 "$url" 2>/dev/null) || exit 0
[ -n "$resp" ] || exit 0

# ── Parse primary condition ID ───────────────────────────────────────────────
# Condition codes: https://openweathermap.org/weather-conditions
# OpenWeather may return multiple entries in weather[]; the first is primary.
if command -v jq >/dev/null 2>&1; then
    code=$(echo "$resp" | jq -r '.weather[0].id // empty' 2>/dev/null)
else
    # Fallback parser if jq is missing — grabs the first "id":NNN it sees.
    code=$(echo "$resp" | grep -oE '"id":[0-9]+' | head -n1 | grep -oE '[0-9]+')
fi
[ -n "${code:-}" ] || exit 0

# ── Map condition code → tag (vocabulary documented at top of file) ──────────
# Only audio-relevant precipitation gets a tag.  Group ranges follow
# OpenWeather's published condition-code table:
#   2xx thunder / 3xx drizzle / 5xx rain / 6xx snow
# All other groups (7xx atmosphere, 8xx clouds/clear) → no tag.
tag=""
case "$code" in
    2*)                              tag="thunderstorm" ;;
    781)                             tag="thunderstorm" ;;   # tornado → strongest tag
    3*)                              tag="rain"         ;;   # drizzle
    500|501|502|511|520|521|531)     tag="rain"         ;;   # light → heavy + freezing + showers
    503|504|522)                     tag="rainstorm"    ;;   # very heavy / extreme / heavy shower
    600|601|611|612|613|615|616|620|621) tag="snow"     ;;   # light → moderate + sleet variants
    602|622)                         tag="snowstorm"    ;;   # heavy snow / heavy shower snow
    *)                               tag=""             ;;   # everything else → no tag
esac

[ -n "$tag" ] && printf '%s' "$tag"
exit 0
