"""
weather.py — a tiny, dependency-free current-weather + sun helper for the digest.

Given a lat/lon (which `location.py` now reads from each `Travel/Cities/*` note),
fetch today's conditions from Open-Meteo (free, no API key) and render a one-line
summary for the morning digest. Everything is best-effort and fails closed: any
network/parse error returns None so the digest never breaks over weather.

Standalone:  python3 weather.py 14.5995 120.9842 Asia/Manila
"""
import os
import sys
import json
import urllib.request
import urllib.parse

# WMO weather-code → (emoji, short description). Coarse buckets are fine for a
# one-line brief. https://open-meteo.com/en/docs (WMO code table).
_WMO = {
    0: ("☀️", "clear"), 1: ("🌤️", "mostly clear"), 2: ("⛅", "partly cloudy"),
    3: ("☁️", "overcast"), 45: ("🌫️", "fog"), 48: ("🌫️", "rime fog"),
    51: ("🌦️", "light drizzle"), 53: ("🌦️", "drizzle"), 55: ("🌦️", "heavy drizzle"),
    61: ("🌧️", "light rain"), 63: ("🌧️", "rain"), 65: ("🌧️", "heavy rain"),
    66: ("🌧️", "freezing rain"), 67: ("🌧️", "freezing rain"),
    71: ("🌨️", "light snow"), 73: ("🌨️", "snow"), 75: ("🌨️", "heavy snow"),
    77: ("🌨️", "snow grains"), 80: ("🌦️", "light showers"), 81: ("🌦️", "showers"),
    82: ("⛈️", "violent showers"), 85: ("🌨️", "snow showers"), 86: ("🌨️", "snow showers"),
    95: ("⛈️", "thunderstorm"), 96: ("⛈️", "thunderstorm + hail"), 99: ("⛈️", "thunderstorm + hail"),
}

UNIT = os.environ.get("DIGEST_TEMP_UNIT", "fahrenheit")      # 'fahrenheit' | 'celsius'
_DEG = "°F" if UNIT == "fahrenheit" else "°C"


def fetch(lat, lon, tz=None, timeout=6):
    """Today's weather for (lat, lon) as a dict, or None on any failure.
    Keys: temp, code, desc, emoji, hi, lo, sunrise, sunset (HH:MM local)."""
    if lat is None or lon is None:
        return None
    q = {
        "latitude": lat, "longitude": lon,
        "current": "temperature_2m,weather_code",
        "daily": "temperature_2m_max,temperature_2m_min,sunrise,sunset",
        "temperature_unit": UNIT,
        "timezone": tz or "auto",
        "forecast_days": 1,
    }
    url = "https://api.open-meteo.com/v1/forecast?" + urllib.parse.urlencode(q)
    try:
        with urllib.request.urlopen(url, timeout=timeout) as r:
            data = json.load(r)
        cur, daily = data["current"], data["daily"]
        code = int(cur["weather_code"])
        emoji, desc = _WMO.get(code, ("🌡️", "—"))
        return {
            "temp": round(cur["temperature_2m"]),
            "code": code, "desc": desc, "emoji": emoji,
            "hi": round(daily["temperature_2m_max"][0]),
            "lo": round(daily["temperature_2m_min"][0]),
            "sunrise": daily["sunrise"][0][11:16],     # ISO 'YYYY-MM-DDTHH:MM'
            "sunset": daily["sunset"][0][11:16],
        }
    except Exception:
        return None


def line(w, location=None):
    """One-line HTML summary (no trailing <br>), or '' if w is falsy."""
    if not w:
        return ""
    where = f"<b>{location}</b> · " if location else ""
    return (f"{w['emoji']} {where}{w['temp']}{_DEG} now ({w['desc']}), "
            f"{w['lo']}–{w['hi']}{_DEG} today · ☀ {w['sunrise']} → {w['sunset']}")


if __name__ == "__main__":
    lat = float(sys.argv[1]); lon = float(sys.argv[2])
    tz = sys.argv[3] if len(sys.argv) > 3 else None
    w = fetch(lat, lon, tz)
    print(w)
    print(line(w, "Test City"))
