#!/bin/bash
# =============================================================================
# Weath — terminal weather by Page Telegram Volunteer Services
# Current conditions, forecast, advisories, query history, ASCII radar, and RSS.
# Radar searches are archived (last 100) for offline review.
# Implementation: weath.impl.sh (this file may be a thin wrapper).
_weath_impl="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/weath.impl.sh"
if [[ -f "$_weath_impl" && "$(basename -- "$0")" != "weath.impl.sh" ]]; then
  exec bash "$_weath_impl" "$@"
fi
# =============================================================================
set -euo pipefail

APP_NAME="Weath"
APP_VENDOR="Page Telegram Volunteer Services"
VERSION="1.0.0"
USER_AGENT="Weath/${VERSION} (${APP_VENDOR}; local; contact:none)"

# Local storage
DATA_DIR="${WEATH_DATA_DIR:-$HOME/.weath}"
HISTORY_FILE="$DATA_DIR/history.jsonl"
LAST_FILE="$DATA_DIR/last.json"
CACHE_DIR="$DATA_DIR/cache"
RADAR_DIR="$DATA_DIR/radar"
RADAR_HISTORY_FILE="$RADAR_DIR/history.jsonl"
RADAR_LAST_FILE="$RADAR_DIR/last.json"
RADAR_FRAMES_DIR="$RADAR_DIR/frames"
RSS_DIR="$DATA_DIR/rss"
RSS_FEEDS_FILE="$RSS_DIR/feeds.json"
GEO_DIR="$DATA_DIR/geo"
ADMIN1_GEOJSON="$GEO_DIR/admin1_states_provinces.geojson"
WATER_OCEAN_GEOJSON="$GEO_DIR/ne_50m_ocean.geojson"
WATER_LAKES_GEOJSON="$GEO_DIR/ne_50m_lakes.geojson"
MAX_HISTORY="${WEATH_MAX_HISTORY:-100}"
MAX_RADAR_HISTORY="${WEATH_MAX_RADAR_HISTORY:-100}"
MAX_RSS_PER_FEED="${WEATH_RSS_PER_FEED:-25}"
MAX_RSS_ITEMS="${WEATH_MAX_RSS:-80}"
RADAR_ZOOM_MIN="${WEATH_RADAR_ZOOM_MIN:-4}"
RADAR_ZOOM_MAX="${WEATH_RADAR_ZOOM_MAX:-11}"
RADAR_AUTO_SEC="${WEATH_RADAR_AUTO_SEC:-300}"

# Last radar shown (used for PNG export)
LAST_RADAR_PNG=""
LAST_RADAR_LABEL=""
LAST_RADAR_WHEN=""
LAST_RADAR_LAT=""
LAST_RADAR_LON=""
LAST_RADAR_ZOOM=""
LAST_RADAR_TX=""
LAST_RADAR_TY=""
LAST_RADAR_BBOX=""
LAST_RADAR_VIEW=""
LAST_RADAR_CROP_STEPS=0
LAST_RADAR_AUTO=0
LAST_RADAR_AUTO_NEXT=0

# Radar glyph: ASCII/Latin-1 code 254 (þ / solid-ish terminal glyph)
RADAR_CHAR=$'\xfe'

# Colors (ANSI)
C_RESET=$'\033[0m'
C_BOLD=$'\033[1m'
C_DIM=$'\033[2m'
C_RED=$'\033[31m'
C_GREEN=$'\033[32m'
C_YELLOW=$'\033[33m'
C_BLUE=$'\033[34m'
C_CYAN=$'\033[36m'
C_WHITE=$'\033[97m'
C_YEL_BRIGHT=$'\033[93m'
C_RED_BRIGHT=$'\033[91m'
C_ORANGE=$'\033[38;5;208m'
C_MAGENTA=$'\033[35m'

# Intensity colors: none / light / moderate / heavy / extreme  (white → yellow → red)
RADAR_COLORS=(
  $'\033[38;5;236m'   # empty / no echo
  $'\033[97m'         # light  — white
  $'\033[93m'         # light-mod — bright yellow
  $'\033[33m'         # moderate — yellow
  $'\033[38;5;208m'   # heavy — orange
  $'\033[91m'         # very heavy — bright red
  $'\033[31;1m'       # extreme — bold red
)

need_cmd() {
  command -v "$1" >/dev/null 2>&1 || {
    echo "Error: required command not found: $1" >&2
    exit 1
  }
}

detect_pkg_manager() {
  if command -v apt-get >/dev/null 2>&1; then
    echo apt
  elif command -v dnf >/dev/null 2>&1; then
    echo dnf
  elif command -v yum >/dev/null 2>&1; then
    echo yum
  elif command -v pacman >/dev/null 2>&1; then
    echo pacman
  elif command -v zypper >/dev/null 2>&1; then
    echo zypper
  elif command -v apk >/dev/null 2>&1; then
    echo apk
  else
    echo ""
  fi
}

pkg_install_cmd() {
  local mgr=$1
  shift
  local sudo_cmd=""
  if [[ "$(id -u)" -ne 0 ]] && command -v sudo >/dev/null 2>&1; then
    sudo_cmd="sudo "
  fi
  case "$mgr" in
    apt) echo "${sudo_cmd}apt-get update && ${sudo_cmd}apt-get install -y $*" ;;
    dnf) echo "${sudo_cmd}dnf install -y $*" ;;
    yum) echo "${sudo_cmd}yum install -y $*" ;;
    pacman) echo "${sudo_cmd}pacman -Sy --noconfirm $*" ;;
    zypper) echo "${sudo_cmd}zypper install -y $*" ;;
    apk) echo "${sudo_cmd}apk add --no-cache $*" ;;
    *) echo "" ;;
  esac
}

ensure_dependencies() {
  local missing_bins=() missing_pkgs=()
  command -v curl >/dev/null 2>&1 || { missing_bins+=(curl); missing_pkgs+=(curl); }
  command -v python3 >/dev/null 2>&1 || { missing_bins+=(python3); missing_pkgs+=(python3); }
  if ! command -v magick >/dev/null 2>&1 && ! command -v convert >/dev/null 2>&1; then
    missing_bins+=("ImageMagick (convert/magick)")
    missing_pkgs+=(imagemagick)
  fi
  if [[ ${#missing_bins[@]} -eq 0 ]]; then
    return 0
  fi
  echo "Missing dependencies:"
  local b
  for b in "${missing_bins[@]}"; do
    echo "  - $b"
  done
  echo
  local mgr cmd
  mgr=$(detect_pkg_manager)
  cmd=$(pkg_install_cmd "$mgr" "${missing_pkgs[@]}")
  if [[ -z "$cmd" ]]; then
    echo "Could not detect a package manager. Install: ${missing_pkgs[*]}"
    echo "Then run weath again."
    exit 1
  fi
  echo "Install with: $cmd"
  local ans=""
  if [[ -t 0 ]]; then
    read -r -p "Install now? [y/N] " ans || true
  else
    echo "Not a terminal; not installing automatically."
    exit 1
  fi
  case "$ans" in
    y|Y|yes|YES)
      echo "Installing..."
      if bash -lc "$cmd"; then
        echo "Install finished."
      else
        echo "Install failed. Install these packages by hand: ${missing_pkgs[*]}" >&2
        exit 1
      fi
      ;;
    *)
      echo "Cannot start without: ${missing_bins[*]}"
      exit 1
      ;;
  esac
  command -v curl >/dev/null 2>&1 || { echo "curl still missing." >&2; exit 1; }
  command -v python3 >/dev/null 2>&1 || { echo "python3 still missing." >&2; exit 1; }
}

init_storage() {
  mkdir -p "$DATA_DIR" "$CACHE_DIR" "$RADAR_FRAMES_DIR" "$RSS_DIR" "$GEO_DIR"
  touch "$HISTORY_FILE" "$RADAR_HISTORY_FILE"
  if [[ ! -s "$RSS_FEEDS_FILE" ]]; then
    printf '%s\n' '[]' > "$RSS_FEEDS_FILE"
  fi
}

banner() {
  echo "${C_CYAN}${C_BOLD}"
  cat <<'EOF'
 __        __          _   _
 \ \      / /__  __ _| |_| |__
  \ \ /\ / / _ \/ _` | __| '_ \
   \ V  V /  __/ (_| | |_| | | |
    \_/\_/ \___|\__,_|\__|_| |_|
EOF
  echo "${C_RESET}${C_DIM}${APP_NAME} v${VERSION} - ${APP_VENDOR}${C_RESET}"
  echo
}

hr() {
  local w
  w=$(tput cols 2>/dev/null || echo 72)
  (( w > 80 )) && w=80
  printf '%*s\n' "$w" '' | tr ' ' '-'
}

# ---------------------------------------------------------------------------
# HTTP helpers
# ---------------------------------------------------------------------------
http_get() {
  local url=$1
  shift
  curl -fsSL --max-time 25 -A "$USER_AGENT" "$@" "$url"
}

http_get_nws() {
  local url=$1
  curl -fsSL --max-time 25 \
    -A "$USER_AGENT" \
    -H "Accept: application/geo+json" \
    "$url"
}

# ---------------------------------------------------------------------------
# Geocoding
# ---------------------------------------------------------------------------
# Returns JSON: {"lat":..,"lon":..,"label":"..","country":"US"|...}
geocode_location() {
  local q=$1
  local cleaned
  cleaned=$(echo "$q" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')

  # US ZIP (5-digit or ZIP+4): pin the geographic CENTER of the ZIP,
  # not a town/PO point that often sits on the edge of the area.
  if [[ "$cleaned" =~ ^[0-9]{5}(-[0-9]{4})?$ ]]; then
    local zip=${cleaned:0:5}
    local zjson njson
    zjson=$(http_get "https://api.zippopotam.us/us/${zip}" 2>/dev/null || true)
    njson=$(http_get \
      "https://nominatim.openstreetmap.org/search?postalcode=${zip}&country=us&format=json&limit=5&polygon_geojson=1&addressdetails=1" \
      -H "Accept-Language: en" 2>/dev/null || true)
    if [[ -n "${zjson:-}" || -n "${njson:-}" ]]; then
      if python3 -c '
import json,sys,math

zip_q=sys.argv[1]
zraw=sys.argv[2]
nraw=sys.argv[3]

def poly_centroid(geom):
    if not geom: return None
    t=geom.get("type"); c=geom.get("coordinates")
    rings=[]
    if t=="Polygon" and c:
        rings.append(c[0])
    elif t=="MultiPolygon" and c:
        # largest outer ring
        best=None; best_a=-1
        for poly in c:
            ring=poly[0] if poly else []
            a=0.0
            for i in range(len(ring)-1):
                a+=ring[i][0]*ring[i+1][1]-ring[i+1][0]*ring[i][1]
            a=abs(a)
            if a>best_a:
                best_a=a; best=ring
        if best: rings.append(best)
    else:
        return None
    ring=rings[0]
    if len(ring)<3: return None
    a=cx=cy=0.0
    for i in range(len(ring)-1):
        x1,y1=float(ring[i][0]), float(ring[i][1])
        x2,y2=float(ring[i+1][0]), float(ring[i+1][1])
        f=x1*y2-x2*y1
        a+=f; cx+=(x1+x2)*f; cy+=(y1+y2)*f
    if abs(a)<1e-18:
        xs=[float(p[0]) for p in ring]; ys=[float(p[1]) for p in ring]
        return sum(ys)/len(ys), sum(xs)/len(xs)
    a*=0.5
    return cy/(6*a), cx/(6*a)

label=None; lat=None; lon=None; bbox=None
if zraw:
    try:
        d=json.loads(zraw)
        p=d["places"][0]
        lat=float(p["latitude"]); lon=float(p["longitude"])
        label="%s, %s %s" % (p["place name"], p["state abbreviation"], d["post code"])
    except Exception:
        pass

if nraw:
    try:
        rows=json.loads(nraw) or []
    except Exception:
        rows=[]
    pick=None
    for r in rows:
        if (r.get("type")=="postcode") or (r.get("class") in ("place","boundary")):
            pick=r; break
    if pick is None and rows:
        pick=rows[0]
    if pick:
        bb=pick.get("boundingbox") or []
        if len(bb)>=4:
            try:
                south,north,west,east=float(bb[0]),float(bb[1]),float(bb[2]),float(bb[3])
                if south<north and west<east:
                    bbox={"south":south,"north":north,"west":west,"east":east}
            except Exception:
                bbox=None
        cen=poly_centroid(pick.get("geojson"))
        if cen:
            lat, lon = cen
        elif bbox:
            # Always use the box center for a ZIP so the pin is not on an edge.
            lat=(bbox["south"]+bbox["north"])/2.0
            lon=(bbox["west"]+bbox["east"])/2.0
        elif pick.get("lat") is not None:
            lat=float(pick["lat"]); lon=float(pick["lon"])
        if not label:
            addr=pick.get("address") or {}
            city=addr.get("town") or addr.get("city") or addr.get("village") or addr.get("county") or ""
            st=addr.get("state") or ""
            bits=[x for x in (city,st,zip_q) if x]
            label=", ".join(bits) if bits else zip_q

if lat is None or lon is None:
    sys.exit(2)
if not bbox:
    dlat=5.0/69.0
    dlon=5.0/max(0.2, 69.0*math.cos(math.radians(lat)))
    bbox={"south": lat-dlat, "north": lat+dlat, "west": lon-dlon, "east": lon+dlon}
print(json.dumps({
  "lat": lat,
  "lon": lon,
  "label": label or zip_q,
  "country": "US",
  "query": zip_q,
  "bbox": bbox,
}))
' "$cleaned" "${zjson:-}" "${njson:-}"; then
        return 0
      fi
    fi
  fi

  # Nominatim (OpenStreetMap). Keep house/POI coordinates; only center
  # ZIP/city/admin areas. Try relaxed names when "X and Y" misses.
  local njson="" alt first=1
  while IFS= read -r alt; do
    [[ -z "$alt" ]] && continue
    if [[ "$first" -eq 1 ]]; then
      first=0
    else
      sleep 1
    fi
    local enc
    enc=$(python3 -c 'import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))' "$alt")
    njson=$(http_get \
      "https://nominatim.openstreetmap.org/search?q=${enc}&format=json&limit=8&addressdetails=1&polygon_geojson=1" \
      -H "Accept-Language: en" 2>/dev/null) || true
    if [[ -n "${njson:-}" && "$njson" != "[]" ]]; then
      break
    fi
  done < <(python3 -c '
import re,sys
q=sys.argv[1].strip()
seen=set(); out=[]
def add(s):
    s=" ".join(s.split())
    k=s.lower()
    if s and k not in seen:
        seen.add(k); out.append(s)
add(q)
no_and=re.sub(r"\s+(and|&)\s+", " ", q, flags=re.I)
add(no_and)
add(re.sub(r"\bcampsites?\b", "campground", q, flags=re.I))
add(re.sub(r"\bcampsites?\b", "campground", no_and, flags=re.I))
words=re.findall(r"[A-Za-z0-9]+", q)
stop={"and","the","at","of","in","on","near"}
core=[w for w in words if w.lower() not in stop]
if len(core)>=2:
    add(" ".join(core[:2]))
for s in out:
    print(s)
' "$cleaned")

  if [[ -n "${njson:-}" && "$njson" != "[]" ]]; then
    local poi_q
    while IFS= read -r poi_q; do
      [[ -z "$poi_q" ]] && continue
      sleep 1
      local penc pjson
      penc=$(python3 -c 'import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))' "$poi_q")
      pjson=$(http_get \
        "https://nominatim.openstreetmap.org/search?q=${penc}&format=json&limit=5&addressdetails=1&polygon_geojson=1" \
        -H "Accept-Language: en" 2>/dev/null) || true
      njson=$(python3 -c '
import json,sys
a=json.loads(sys.argv[1] or "[]")
b=json.loads(sys.argv[2] or "[]")
seen=set(); out=[]
for r in list(a)+list(b):
    k=(r.get("osm_type"), r.get("osm_id"), r.get("lat"), r.get("lon"))
    if k in seen:
        continue
    seen.add(k); out.append(r)
print(json.dumps(out))
' "$njson" "${pjson:-[]}")
    done < <(python3 -c '
import json,sys
rows=json.loads(sys.argv[1] or "[]")
seen=set(); out=[]
def add(s):
    s=" ".join(s.split())
    k=s.lower()
    if s and k not in seen:
        seen.add(k); out.append(s)
for r in rows:
    addr=r.get("address") or {}
    if not (addr.get("house_number") or r.get("type")=="house"):
        continue
    city=addr.get("village") or addr.get("city") or addr.get("town") or ""
    st=addr.get("state") or ""
    if not city:
        break
    loc=city + ((", "+st) if st else "")
    add("campground, "+loc)
    add("beach, "+loc)
    break
print("\n".join(out))
' "$njson")
  fi

  if [[ -n "${njson:-}" && "$njson" != "[]" ]]; then
    python3 -c '
import json,sys,math,re
q=sys.argv[1]
rows=json.load(sys.stdin)
if not rows:
    sys.exit(2)

AREA_TYPES={"postcode","administrative","postal_code","city","town","village",
            "hamlet","county","state","municipality","suburb","neighbourhood",
            "neighborhood","district","region","township"}
PRECISE_TYPES={"house","yes","residential","apartments","building","cabin",
               "camp_site","caravan_site","picnic_site","hostel","hotel","motel",
               "guest_house","attraction","museum","park","beach","marina",
               "restaurant","cafe","bar","fast_food","parking"}
PRECISE_CLASS={"amenity","tourism","leisure","natural","shop","office",
               "craft","healthcare","historic","sport","building"}

def is_precise(r):
    addr=r.get("address") or {}
    if addr.get("house_number"):
        return True
    t=r.get("type") or ""
    if t in PRECISE_TYPES:
        return True
    if (r.get("class") in PRECISE_CLASS) and t not in AREA_TYPES:
        return True
    return False

def is_area(r):
    t=r.get("type") or ""
    if t in AREA_TYPES:
        return True
    return r.get("class")=="boundary" and t=="administrative"

def tokens(s):
    return [t for t in re.findall(r"[a-z0-9]+", (s or "").lower()) if t not in {"and","the","at","of","in","on","near","us","usa"}]

qt=tokens(q)
qhead=" ".join(qt[:4])

def score(r):
    s=0
    addr=r.get("address") or {}
    cc=(addr.get("country_code") or "").lower()
    if cc=="us": s+=10
    name=(r.get("name") or addr.get(r.get("type") or "") or addr.get("tourism") or addr.get("leisure") or "")
    disp=(r.get("display_name") or "")
    nt=tokens(name)+tokens(disp)
    if qt:
        overlap=len(set(qt) & set(nt))
        s+=overlap*3
        if name and qhead and qhead in " ".join(tokens(name)):
            s+=8
    if is_precise(r):
        s+=8
    elif is_area(r):
        s+=2
    if r.get("class") in ("place","boundary") and not is_precise(r):
        s+=1
    try:
        s+=min(2.0, float(r.get("importance") or 0))
    except Exception:
        pass
    return s

rows.sort(key=score, reverse=True)
r=rows[0]
addr=r.get("address") or {}
name=(r.get("name") or addr.get(r.get("addresstype") or "") or
      addr.get("tourism") or addr.get("leisure") or addr.get("amenity") or
      addr.get("natural") or "")
hn=addr.get("house_number") or ""
road=addr.get("road") or addr.get("pedestrian") or ""
locality=""
for k in ("city","town","village","hamlet","suburb","county"):
    if addr.get(k):
        locality=addr[k]; break
st=addr.get("state") or addr.get("state_code") or ""
pc=addr.get("postcode") or ""
parts=[]
if hn and road:
    parts.append("%s %s" % (hn, road))
elif name and (not locality or name.lower()!=locality.lower()):
    parts.append(name)
elif road:
    parts.append(road)
if locality:
    parts.append(locality)
if st:
    parts.append(st)
if pc:
    parts.append(pc)
if not parts:
    parts=[(r.get("display_name") or "Unknown")[:60]]
cc=(addr.get("country_code") or "").upper()
lat=float(r["lat"]); lon=float(r["lon"])
bbox=None
bb=r.get("boundingbox") or []
if len(bb)>=4:
    try:
        south,north,west,east=float(bb[0]),float(bb[1]),float(bb[2]),float(bb[3])
        if south<north and west<east:
            bbox={"south":south,"north":north,"west":west,"east":east}
    except Exception:
        bbox=None

def poly_centroid(geom):
    if not geom: return None
    t=geom.get("type"); c=geom.get("coordinates")
    ring=None
    if t=="Polygon" and c:
        ring=c[0]
    elif t=="MultiPolygon" and c:
        best=None; best_a=-1
        for poly in c:
            rr=poly[0] if poly else []
            a=0.0
            for i in range(len(rr)-1):
                a+=rr[i][0]*rr[i+1][1]-rr[i+1][0]*rr[i][1]
            a=abs(a)
            if a>best_a:
                best_a=a; best=rr
        ring=best
    if not ring or len(ring)<3:
        return None
    a=cx=cy=0.0
    for i in range(len(ring)-1):
        x1,y1=float(ring[i][0]), float(ring[i][1])
        x2,y2=float(ring[i+1][0]), float(ring[i+1][1])
        f=x1*y2-x2*y1
        a+=f; cx+=(x1+x2)*f; cy+=(y1+y2)*f
    if abs(a)<1e-18:
        return None
    a*=0.5
    return cy/(6*a), cx/(6*a)

# Houses, campsites, beaches, and other POIs keep the geocoder point.
# Only city / ZIP / admin areas are pinned to a polygon or box center.
if is_area(r) and not is_precise(r):
    cen=poly_centroid(r.get("geojson"))
    if cen:
        lat, lon = cen
    elif bbox:
        lat=(bbox["south"]+bbox["north"])/2.0
        lon=(bbox["west"]+bbox["east"])/2.0

def hav_mi(lat1, lon1, lat2, lon2):
    p1,p2=math.radians(lat1),math.radians(lat2)
    dph=math.radians(lat2-lat1)
    dl=math.radians(lon2-lon1)
    a=math.sin(dph/2)**2+math.cos(p1)*math.cos(p2)*math.sin(dl/2)**2
    return 2*3958.8*math.asin(min(1.0, math.sqrt(a)))

def is_water_poi(o):
    t=o.get("type") or ""
    cl=o.get("class") or ""
    if t in ("beach","camp_site","caravan_site","marina"):
        return True
    if cl=="natural" and t=="beach":
        return True
    if cl=="tourism" and t in ("camp_site","caravan_site"):
        return True
    return False

snapped=False
if (r.get("type")=="house" or hn) and not (is_area(r) and not is_precise(r)):
    best=None
    best_d=0.6
    for o in rows:
        if o is r or not is_water_poi(o):
            continue
        try:
            olat,olon=float(o["lat"]),float(o["lon"])
        except Exception:
            continue
        d=hav_mi(lat, lon, olat, olon)
        ob=o.get("boundingbox") or []
        if len(ob)>=4:
            try:
                os_,on_,ow,oe=map(float, ob[:4])
                if os_<=lat<=on_ and ow<=lon<=oe:
                    d=min(d, 0.01)
            except Exception:
                pass
        if d<best_d:
            best=o; best_d=d
    if best is not None:
        lat=float(best["lat"]); lon=float(best["lon"])
        snapped=True
        nm=best.get("name") or ""
        if nm and nm.lower() not in ", ".join(parts).lower():
            if hn and road:
                parts.insert(1, nm)
            else:
                parts.insert(0, nm)
        bb=best.get("boundingbox") or []
        if len(bb)>=4:
            try:
                south,north,west,east=float(bb[0]),float(bb[1]),float(bb[2]),float(bb[3])
                if south<north and west<east:
                    bbox={"south":south,"north":north,"west":west,"east":east}
            except Exception:
                pass

if not bbox:
    dlat=5.0/69.0
    dlon=5.0/max(0.2, 69.0*math.cos(math.radians(lat)))
    bbox={"south":lat-dlat,"north":lat+dlat,"west":lon-dlon,"east":lon+dlon}
precise=bool(snapped or (is_precise(r) and not is_area(r)))
print(json.dumps({
  "lat": lat,
  "lon": lon,
  "label": ", ".join(parts),
  "country": cc,
  "query": q,
  "bbox": bbox,
  "precise": precise,
}))
' "$cleaned" <<<"$njson" && return 0
  fi

  # wttr.in location resolve fallback (returns nearest area via j1)
  local wjson
  wjson=$(http_get "https://wttr.in/$(python3 -c 'import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))' "$cleaned")?format=j1" 2>/dev/null) || true
  if [[ -n "${wjson:-}" ]]; then
    python3 -c '
import json,sys,math
d=json.load(sys.stdin)
a=d["nearest_area"][0]
lat=float(a["latitude"]); lon=float(a["longitude"])
name=a["areaName"][0]["value"]
region=a["region"][0]["value"]
country=a["country"][0]["value"]
dlat=5.0/69.0
dlon=5.0/max(0.2, 69.0*math.cos(math.radians(lat)))
print(json.dumps({
  "lat": lat, "lon": lon,
  "label": f"{name}, {region}",
  "country": "US" if country in ("United States of America","USA","United States") else country,
  "query": sys.argv[1],
  "bbox": {"south": lat-dlat, "north": lat+dlat, "west": lon-dlon, "east": lon+dlon},
}))
' "$cleaned" <<<"$wjson" && return 0
  fi

  echo "Error: could not geocode location: $cleaned" >&2
  return 1
}

# ---------------------------------------------------------------------------
# Weather providers
# ---------------------------------------------------------------------------
fetch_nws() {
  local lat=$1 lon=$2
  local points forecast_url stations_url county_url
  points=$(http_get_nws "https://api.weather.gov/points/${lat},${lon}") || return 1

  python3 -c '
import json,sys,urllib.request,os
points=json.load(sys.stdin)
p=points["properties"]
lat=float(sys.argv[1]); lon=float(sys.argv[2])
ua=os.environ.get("WEATH_UA","Weath/1.0")
def get(url):
    req=urllib.request.Request(url, headers={"User-Agent":ua,"Accept":"application/geo+json"})
    with urllib.request.urlopen(req, timeout=25) as r:
        return json.load(r)

rel=p.get("relativeLocation",{}).get("properties",{})
city=rel.get("city") or ""
state=rel.get("state") or ""
label=", ".join(x for x in (city,state) if x)

forecast=get(p["forecast"])
periods=forecast["properties"]["periods"]

obs=None
obs_url=None
try:
    stations=get(p["observationStations"])
    feats=stations.get("features") or []
    if feats:
        obs_url=feats[0]["id"]+"/observations/latest"
        obs=get(obs_url)["properties"]
except Exception:
    obs=None

alerts=[]
try:
    al=get(f"https://api.weather.gov/alerts/active?point={lat},{lon}")
    for f in al.get("features") or []:
        pr=f.get("properties") or {}
        alerts.append({
            "event": pr.get("event") or "Alert",
            "severity": pr.get("severity") or "",
            "headline": pr.get("headline") or pr.get("event") or "",
            "description": (pr.get("description") or "")[:500],
            "instruction": (pr.get("instruction") or "")[:300],
            "ends": pr.get("ends") or pr.get("expires") or "",
        })
except Exception:
    pass

def c_to_f(v):
    if v is None: return None
    return round(v*9/5+32)

def kmh_to_mph(v):
    if v is None: return None
    return round(v*0.621371,1)

def m_to_mi(v):
    if v is None: return None
    return round(v/1609.344,1)

cur={}
if obs:
    t=obs.get("temperature") or {}
    tv=t.get("value")
    unit=(t.get("unitCode") or "")
    if tv is not None:
        if "degC" in unit: tv=c_to_f(tv)
        else: tv=round(tv)
    ws=obs.get("windSpeed") or {}
    wsv=ws.get("value")
    if wsv is not None and "km_h" in (ws.get("unitCode") or ""):
        wsv=kmh_to_mph(wsv)
    elif wsv is not None:
        wsv=round(wsv,1)
    rh=(obs.get("relativeHumidity") or {}).get("value")
    if rh is not None: rh=round(rh)
    vis=(obs.get("visibility") or {}).get("value")
    if vis is not None: vis=m_to_mi(vis)
    wd=(obs.get("windDirection") or {}).get("value")
    cur={
        "temp_f": tv,
        "desc": obs.get("textDescription") or "",
        "humidity": rh,
        "wind_mph": wsv,
        "wind_dir": wd,
        "visibility_mi": vis,
        "dewpoint_f": c_to_f((obs.get("dewpoint") or {}).get("value")),
        "time": obs.get("timestamp") or "",
        "source": "NWS observation",
    }
else:
    # Use first forecast period as stand-in
    pe=periods[0] if periods else {}
    cur={
        "temp_f": pe.get("temperature"),
        "desc": pe.get("shortForecast") or "",
        "humidity": None,
        "wind_mph": None,
        "wind_dir": None,
        "visibility_mi": None,
        "dewpoint_f": None,
        "time": pe.get("startTime") or "",
        "source": "NWS forecast (no observation)",
        "wind": pe.get("windSpeed") or "",
        "windDirection": pe.get("windDirection") or "",
    }

def pop_pct(pe):
    pop=pe.get("probabilityOfPrecipitation") or {}
    v=pop.get("value") if isinstance(pop, dict) else pop
    if v is None:
        return None
    try:
        return int(round(float(v)))
    except (TypeError, ValueError):
        return None

fc=[]
for pe in periods[:14]:
    fc.append({
        "name": pe.get("name") or "",
        "temp": pe.get("temperature"),
        "unit": pe.get("temperatureUnit") or "F",
        "wind": pe.get("windSpeed") or "",
        "wind_dir": pe.get("windDirection") or "",
        "short": pe.get("shortForecast") or "",
        "detailed": pe.get("detailedForecast") or "",
        "is_day": pe.get("isDaytime", True),
        "precip_pct": pop_pct(pe),
    })

out={
    "provider": "nws",
    "lat": lat, "lon": lon,
    "label": label or f"{lat:.4f},{lon:.4f}",
    "current": cur,
    "forecast": fc,
    "alerts": alerts,
}
print(json.dumps(out))
' "$lat" "$lon" <<<"$points"
}

fetch_wttr() {
  local query=$1
  local enc
  enc=$(python3 -c 'import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))' "$query")
  local wjson
  wjson=$(http_get "https://wttr.in/${enc}?format=j1") || return 1
  python3 -c '
import json,sys
d=json.load(sys.stdin)
c=d["current_condition"][0]
a=d["nearest_area"][0]
name=a["areaName"][0]["value"]
region=a["region"][0]["value"]
country=a["country"][0]["value"]
label=f"{name}, {region}"
cur={
  "temp_f": int(c.get("temp_F") or 0),
  "desc": c["weatherDesc"][0]["value"],
  "humidity": int(c.get("humidity") or 0),
  "wind_mph": float(c.get("windspeedMiles") or 0),
  "wind_dir": c.get("winddir16Point") or c.get("winddirDegree"),
  "visibility_mi": float(c.get("visibilityMiles") or 0) if c.get("visibilityMiles") else None,
  "dewpoint_f": int(c.get("DewPointF") or 0) if c.get("DewPointF") else None,
  "feels_like_f": int(c.get("FeelsLikeF") or 0) if c.get("FeelsLikeF") else None,
  "time": c.get("localObsDateTime") or c.get("observation_time") or "",
  "source": "wttr.in",
}
def day_precip_pct(day):
    best=None
    for h in day.get("hourly") or []:
        for k in ("chanceofrain","chanceofsnow","chanceofthunder","chanceofprecip"):
            raw=h.get(k)
            if raw in (None,""):
                continue
            try:
                v=int(round(float(raw)))
            except (TypeError, ValueError):
                continue
            if best is None or v>best:
                best=v
    return best

fc=[]
for day in d.get("weather") or []:
    date=day.get("date") or ""
    hourly=day.get("hourly") or [{}]
    mid=hourly[4] if len(hourly)>4 else hourly[-1]
    fc.append({
        "name": date,
        "temp": int(day.get("maxtempF") or 0),
        "temp_min": int(day.get("mintempF") or 0),
        "unit": "F",
        "wind": "",
        "wind_dir": "",
        "short": (mid.get("weatherDesc") or [{"value":""}])[0].get("value") or "",
        "detailed": "",
        "is_day": True,
        "precip_pct": day_precip_pct(day),
    })
    # also add a night-ish summary via min
alerts=[]
# wttr does not provide NWS advisories
out={
  "provider": "wttr",
  "lat": float(a["latitude"]),
  "lon": float(a["longitude"]),
  "label": label,
  "country": country,
  "current": cur,
  "forecast": fc,
  "alerts": alerts,
}
print(json.dumps(out))
' <<<"$wjson"
}

fetch_weather() {
  local geo_json=$1
  local lat lon country query label
  lat=$(python3 -c 'import json,sys; print(json.load(sys.stdin)["lat"])' <<<"$geo_json")
  lon=$(python3 -c 'import json,sys; print(json.load(sys.stdin)["lon"])' <<<"$geo_json")
  country=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("country",""))' <<<"$geo_json")
  query=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("query",""))' <<<"$geo_json")
  label=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("label",""))' <<<"$geo_json")

  export WEATH_UA="$USER_AGENT"
  local weather=""
  if [[ "$country" == "US" || "$country" == "USA" || "$country" == "United States" ]]; then
    weather=$(fetch_nws "$lat" "$lon" 2>/dev/null || true)
  fi
  if [[ -z "${weather:-}" ]]; then
    weather=$(fetch_wttr "${query:-$label}" 2>/dev/null || fetch_wttr "${lat},${lon}" 2>/dev/null || true)
  fi
  if [[ -z "${weather:-}" ]]; then
    echo "Error: could not fetch weather for $label" >&2
    return 1
  fi

  # Merge geo label if weather label empty; attach geo + timestamp
  python3 -c '
import json,sys,datetime
geo=json.loads(sys.argv[1])
w=json.load(sys.stdin)
# Prefer geocoder label and coordinates so weather fallbacks (wttr
# nearest_area) cannot move the pin off the typed address.
if geo.get("label"):
    w["label"]=geo["label"]
if geo.get("lat") is not None and geo.get("lon") is not None:
    w["lat"]=geo["lat"]
    w["lon"]=geo["lon"]
if geo.get("bbox"):
    w["bbox"]=geo["bbox"]
w["geo"]=geo
w["fetched_at"]=datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
w["query"]=geo.get("query") or w.get("label")
print(json.dumps(w))
' "$geo_json" <<<"$weather"
}

# ---------------------------------------------------------------------------
# History
# ---------------------------------------------------------------------------
save_history() {
  local weather_json=$1
  python3 -c '
import json,sys,os,tempfile
path=sys.argv[1]
max_h=int(sys.argv[2])
last_path=sys.argv[3]
rec=json.load(sys.stdin)
# compact history entry
entry={
  "fetched_at": rec.get("fetched_at"),
  "query": rec.get("query"),
  "label": rec.get("label"),
  "lat": rec.get("lat"),
  "lon": rec.get("lon"),
  "provider": rec.get("provider"),
  "current": rec.get("current"),
  "forecast": (rec.get("forecast") or [])[:6],
  "alerts": rec.get("alerts") or [],
}
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
with open(path,"a",encoding="utf-8") as f:
    f.write(json.dumps(entry, ensure_ascii=False)+"\n")
# trim
try:
    with open(path,encoding="utf-8") as f:
        lines=[ln for ln in f if ln.strip()]
    if len(lines)>max_h:
        lines=lines[-max_h:]
        with open(path,"w",encoding="utf-8") as f:
            f.writelines(lines)
except Exception:
    pass
with open(last_path,"w",encoding="utf-8") as f:
    json.dump(rec, f, ensure_ascii=False, indent=2)
' "$HISTORY_FILE" "$MAX_HISTORY" "$LAST_FILE" <<<"$weather_json"
}

load_last() {
  [[ -f "$LAST_FILE" ]] || return 1
  cat "$LAST_FILE"
}

history_count() {
  [[ -f "$HISTORY_FILE" ]] || { echo 0; return; }
  grep -c . "$HISTORY_FILE" 2>/dev/null || echo 0
}

radar_history_count() {
  [[ -f "$RADAR_HISTORY_FILE" ]] || { echo 0; return; }
  grep -c . "$RADAR_HISTORY_FILE" 2>/dev/null || echo 0
}

# ---------------------------------------------------------------------------
# Display
# ---------------------------------------------------------------------------
deg_to_compass() {
  local d=$1
  python3 -c '
import sys
try:
    d=float(sys.argv[1])
except Exception:
    print(sys.argv[1]); raise SystemExit
dirs=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"]
print(dirs[int((d+11.25)%360//22.5)])
' "$d" 2>/dev/null || echo "$d"
}

print_weather() {
  local weather_json=$1
  local title_note=${2:-}
  WEATH_PAYLOAD="$weather_json" python3 - "$title_note" <<'PY'
import json,sys,textwrap,os

note=sys.argv[1] if len(sys.argv)>1 else ""
w=json.loads(os.environ["WEATH_PAYLOAD"])
c=w.get("current") or {}
R="\033[0m"; B="\033[1m"; D="\033[2m"
CYAN="\033[36m"; YEL="\033[33m"; RED="\033[31m"; GRN="\033[32m"; MAG="\033[35m"; WHT="\033[97m"

def hr():
    print("-"*64)

label=w.get("label") or "Unknown"
query=w.get("query") or ""
fetched=w.get("fetched_at") or ""
print(f"{B}{CYAN}{label}{R}")
if query and query != label:
    print(f"{D}  query: {query}{R}")
if note:
    print(f"{D}  {note}{R}")
if fetched:
    print(f"{D}  fetched: {fetched}  -  provider: {w.get('provider','?')}{R}")
hr()

temp=c.get("temp_f")
desc=c.get("desc") or "-"
print(f"{B}{WHT}  Current conditions{R}")
if temp is not None:
    print(f"  {B}{temp}°F{R}  {desc}")
else:
    print(f"  {desc}")

bits=[]
if c.get("feels_like_f") is not None:
    bits.append(f"feels {c['feels_like_f']}°F")
if c.get("humidity") is not None:
    bits.append(f"humidity {c['humidity']}%")
if c.get("dewpoint_f") is not None:
    bits.append(f"dewpoint {c['dewpoint_f']}°F")
wind_s=None
if c.get("wind_mph") is not None:
    try:
        wmph=float(c["wind_mph"])
    except (TypeError, ValueError):
        wmph=None
    if wmph is not None and wmph < 0.5:
        wind_s="wind calm"
    elif wmph is not None:
        wd=c.get("wind_dir")
        if isinstance(wd,(int,float)):
            dirs=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"]
            wd=dirs[int((float(wd)+11.25)%360//22.5)]
        wind_s=f"wind {wmph:g} mph" + (f" {wd}" if wd not in (None,"") else "")
elif c.get("wind"):
    wind_s=f"wind {c.get('wind','')} {c.get('windDirection') or c.get('wind_dir') or ''}".strip()
if wind_s:
    bits.append(wind_s)
if c.get("visibility_mi") is not None:
    bits.append(f"vis {c['visibility_mi']} mi")
if bits:
    print(f"  {D}{' | '.join(bits)}{R}")
if c.get("time"):
    print(f"  {D}observed: {c['time']}{R}")
if c.get("source"):
    print(f"  {D}source: {c['source']}{R}")

alerts=w.get("alerts") or []
print()
print(f"{B}{RED}  Advisories{R}" if alerts else f"{B}  Advisories{R}")
hr()
if not alerts:
    print(f"  {GRN}No active advisories for this location.{R}")
else:
    for a in alerts:
        sev=a.get("severity") or ""
        print(f"  {B}{RED}! {a.get('event','Alert')}{R}  {D}{sev}{R}")
        if a.get("headline"):
            for line in textwrap.wrap(a["headline"], 60):
                print(f"    {line}")
        if a.get("ends"):
            print(f"    {D}until {a['ends']}{R}")
        if a.get("description"):
            for line in textwrap.wrap(a["description"].replace("\n"," "), 60)[:6]:
                print(f"    {D}{line}{R}")
        print()

fc=w.get("forecast") or []
print(f"{B}{YEL}  Forecast{R}")
hr()
if not fc:
    print(f"  {D}No forecast data.{R}")
else:
    for p in fc[:12]:
        name=p.get("name") or ""
        temp=p.get("temp")
        unit=p.get("unit") or "F"
        short=p.get("short") or ""
        tmin=p.get("temp_min")
        if tmin is not None:
            temps=f"{temp}°/{tmin}°{unit}"
        elif temp is not None:
            temps=f"{temp}°{unit}"
        else:
            temps=""
        wind=p.get("wind") or ""
        wdir=p.get("wind_dir") or ""
        extra=f"  {D}{wind} {wdir}{R}".rstrip() if wind else ""
        pop=p.get("precip_pct")
        if pop is None:
            precip="--%"
        else:
            try:
                precip="%d%%" % int(pop)
            except (TypeError, ValueError):
                precip="--%"
        print(f"  {B}{name:<18}{R} {temps:<10} {precip:<5} precip  {short}{extra}")
        det=p.get("detailed") or ""
        if det and os.environ.get("WEATH_DETAIL")=="1":
            for line in textwrap.wrap(det, 58)[:3]:
                print(f"    {D}{line}{R}")
print()
PY
}

print_history_list() {
  if [[ ! -s "$HISTORY_FILE" ]]; then
    echo "No history yet. Look up a location first."
    return 0
  fi
  python3 -c "
import json,sys
path=sys.argv[1]
rows=[]
with open(path,encoding='utf-8') as f:
    for i,ln in enumerate(f,1):
        ln=ln.strip()
        if not ln: continue
        try:
            rows.append(json.loads(ln))
        except Exception:
            pass
# file order is oldest→newest; display newest first as #1
rows.reverse()
print('#   %-22s  %-32s  %-5s %s' % ('When','Location','Temp','Conditions'))
print('-'*78)
for num, r in enumerate(rows, 1):
    cur=r.get('current') or {}
    t=cur.get('temp_f')
    ts=(r.get('fetched_at') or '')[:19].replace('T',' ')
    lab=(r.get('label') or r.get('query') or '?')[:32]
    desc=(cur.get('desc') or '')[:24]
    tstr=('%s degF' % t) if t is not None else '-'
    print('%-3d %-22s  %-32s  %-5s %s' % (num, ts, lab, tstr, desc))
print()
print('Tip: weath --history N   show full entry N (1 = most recent)')
" "$HISTORY_FILE"
}

show_history_entry() {
  local n=$1
  python3 -c '
import json,sys
path=sys.argv[1]
n=int(sys.argv[2])
rows=[]
with open(path,encoding="utf-8") as f:
    for ln in f:
        ln=ln.strip()
        if ln:
            try: rows.append(json.loads(ln))
            except: pass
if not rows:
    print("No history.", file=sys.stderr); sys.exit(1)
# 1 = most recent
idx=len(rows)-n
if idx<0 or idx>=len(rows):
    print(f"No history entry #{n}. Have {len(rows)} entries.", file=sys.stderr)
    sys.exit(1)
print(json.dumps(rows[idx]))
' "$HISTORY_FILE" "$n"
}

# ---------------------------------------------------------------------------
# Radar (RainViewer tiles → terminal grid of ASCII 254)
# Last 100 searches are archived under $RADAR_DIR for offline review.
# ---------------------------------------------------------------------------
# Print south,north,west,east from a geo/weather/radar JSON record.
bbox_csv_from_json() {
  python3 -c '
import json,sys,math
d=json.load(sys.stdin)
bb=d.get("bbox") or (d.get("geo") or {}).get("bbox")
if isinstance(bb, dict) and all(k in bb for k in ("south","north","west","east")):
    print("%.6f,%.6f,%.6f,%.6f" % (
        float(bb["south"]), float(bb["north"]), float(bb["west"]), float(bb["east"])))
    raise SystemExit
lat=d.get("lat"); lon=d.get("lon")
if lat is None:
    g=d.get("geo") or {}
    lat=g.get("lat"); lon=g.get("lon")
if lat is None or lon is None:
    raise SystemExit(0)
lat=float(lat); lon=float(lon)
dlat=5.0/69.0
dlon=5.0/max(0.2, 69.0*math.cos(math.radians(lat)))
print("%.6f,%.6f,%.6f,%.6f" % (lat-dlat, lat+dlat, lon-dlon, lon+dlon))
'
}

approx_bbox_csv() {
  python3 -c '
import math,sys
lat=float(sys.argv[1]); lon=float(sys.argv[2])
dlat=5.0/69.0
dlon=5.0/max(0.2, 69.0*math.cos(math.radians(lat)))
print("%.6f,%.6f,%.6f,%.6f" % (lat-dlat, lat+dlat, lon-dlon, lon+dlon))
' "$1" "$2"
}

ensure_admin1_geojson() {
  [[ -s "$ADMIN1_GEOJSON" ]] && return 0
  mkdir -p "$GEO_DIR"
  local url part
  part="$ADMIN1_GEOJSON.part"
  for url in \
    "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_50m_admin_1_states_provinces.geojson" \
    "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_110m_admin_1_states_provinces.geojson"
  do
    if curl -fsSL --max-time 60 -A "$USER_AGENT" -o "$part" "$url" 2>/dev/null \
      && python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); assert d.get("features")' "$part" 2>/dev/null; then
      mv "$part" "$ADMIN1_GEOJSON"
      return 0
    fi
  done
  rm -f "$part"
  return 1
}

# Oceans + lakes (Natural Earth 50m). Lake Michigan and the other Great Lakes
# are in the lakes file; Carto dark tiles are grayscale and cannot mark them.
ensure_water_geojson() {
  mkdir -p "$GEO_DIR"
  local dest url part ok
  ok=0
  for dest in "$WATER_OCEAN_GEOJSON" "$WATER_LAKES_GEOJSON"; do
    if [[ -s "$dest" ]]; then
      ok=1
      continue
    fi
    case "$dest" in
      *ocean*) url="https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_50m_ocean.geojson" ;;
      *) url="https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_50m_lakes.geojson" ;;
    esac
    part="$dest.part"
    if curl -fsSL --max-time 90 -A "$USER_AGENT" -o "$part" "$url" 2>/dev/null \
      && python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); assert d.get("features")' "$part" 2>/dev/null; then
      mv "$part" "$dest"
      ok=1
    else
      rm -f "$part"
    fi
  done
  [[ "$ok" -eq 1 ]]
}

# Filled water mask. mode=cells -> "x y" per water pixel.
raster_water() {
  local dest=$1 w=$2 h=$3 south=$4 north=$5 west=$6 east=$7
  local have=0
  [[ -s "$WATER_OCEAN_GEOJSON" ]] && have=1
  [[ -s "$WATER_LAKES_GEOJSON" ]] && have=1
  [[ "$have" -eq 1 ]] || return 1
  python3 -c '
import json,math,sys,os

dest, w, h = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
south, north, west, east = map(float, sys.argv[4:8])
paths = [p for p in sys.argv[8:] if p and os.path.isfile(p) and os.path.getsize(p)>0]
if east==west or north==south or w<2 or h<2 or not paths:
    sys.exit(1)

def merc_y(la):
    la=max(-85.05112878, min(85.05112878, float(la)))
    return math.asinh(math.tan(math.radians(la)))

mn, ms = merc_y(north), merc_y(south)

def project(lo, la):
    fx=(float(lo)-west)/(east-west)*(w-1)
    fy=(mn-merc_y(la))/(mn-ms)*(h-1)
    return fx, fy

def rings_of(geom):
    if not geom:
        return
    t=geom.get("type")
    c=geom.get("coordinates") or []
    if t=="Polygon":
        for r in c: yield r
    elif t=="MultiPolygon":
        for poly in c:
            for r in poly: yield r

def feat_bb(feat):
    b=feat.get("bbox")
    if b and len(b)>=4:
        return float(b[0]), float(b[1]), float(b[2]), float(b[3])
    xs=[]; ys=[]
    for ring in rings_of(feat.get("geometry") or {}):
        for pt in ring:
            if len(pt)>=2:
                xs.append(float(pt[0])); ys.append(float(pt[1]))
    if not xs:
        return None
    return min(xs), min(ys), max(xs), max(ys)

# Pad so lake edges that clip the frame still fill.
pad_x=(east-west)*0.02
pad_y=(north-south)*0.02
vw, ve = west-pad_x, east+pad_x
vs, vn = south-pad_y, north+pad_y

mask=[[0]*w for _ in range(h)]
edges=[]
for path in paths:
    try:
        data=json.load(open(path, encoding="utf-8"))
    except Exception:
        continue
    for feat in data.get("features") or []:
        bb=feat_bb(feat)
        if bb:
            minx,miny,maxx,maxy=bb
            if maxx<vw or minx>ve or maxy<vs or miny>vn:
                continue
        for ring in rings_of(feat.get("geometry") or {}):
            pts=[]
            for pt in ring:
                if len(pt)<2:
                    continue
                lo, la = float(pt[0]), float(pt[1])
                if pts:
                    plo=pts[-1][2]
                    if abs(lo-plo)>180:
                        if len(pts)>=3:
                            edges.append(pts)
                        pts=[]
                x,y=project(lo, la)
                pts.append((x,y,lo))
            if len(pts)>=3:
                edges.append(pts)

# Even-odd scanline fill, sample at pixel centers.
for y in range(h):
    ys=float(y)
    xs=[]
    for pts in edges:
        n=len(pts)
        for i in range(n):
            x0,y0=pts[i][0], pts[i][1]
            j=i+1 if i+1<n else 0
            x1,y1=pts[j][0], pts[j][1]
            if y0==y1:
                continue
            if y0>y1:
                x0,y0,x1,y1=x1,y1,x0,y0
            if y0 <= ys < y1:
                t=(ys-y0)/(y1-y0)
                xs.append(x0+t*(x1-x0))
    xs.sort()
    for i in range(0, len(xs)-1, 2):
        xa, xb = xs[i], xs[i+1]
        x0i=max(0, int(math.ceil(xa)))
        x1i=min(w-1, int(math.floor(xb)))
        for x in range(x0i, x1i+1):
            mask[y][x]=1

with open(dest, "w", encoding="utf-8") as fh:
    for y in range(h):
        for x in range(w):
            if mask[y][x]:
                fh.write("%d %d\n" % (x,y))
' "$dest" "$w" "$h" "$south" "$north" "$west" "$east" \
    "$WATER_OCEAN_GEOJSON" "$WATER_LAKES_GEOJSON"
}

# mode=cells -> text "x y" per pixel; mode=ppm -> binary P6 image
raster_admin1() {
  local mode=$1 dest=$2 w=$3 h=$4 south=$5 north=$6 west=$7 east=$8
  [[ -s "$ADMIN1_GEOJSON" ]] || return 1
  python3 -c '
import json,math,sys
mode, dest, w, h = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])
south, north, west, east = map(float, sys.argv[5:9])
path = sys.argv[9]
if east==west or north==south or w<2 or h<2:
    sys.exit(1)

def merc_y(la):
    la=max(-85.05112878, min(85.05112878, float(la)))
    return math.asinh(math.tan(math.radians(la)))

mn, ms = merc_y(north), merc_y(south)

def project(lo, la):
    fx=(float(lo)-west)/(east-west)*(w-1)
    fy=(mn-merc_y(la))/(mn-ms)*(h-1)
    return fx, fy

def bres(x0,y0,x1,y1):
    x0=int(round(x0)); y0=int(round(y0))
    x1=int(round(x1)); y1=int(round(y1))
    dx=abs(x1-x0); sx=1 if x0<x1 else -1
    dy=-abs(y1-y0); sy=1 if y0<y1 else -1
    err=dx+dy
    while True:
        if 0<=x0<w and 0<=y0<h:
            yield x0,y0
        if x0==x1 and y0==y1:
            break
        e2=2*err
        if e2>=dy:
            err+=dy; x0+=sx
        if e2<=dx:
            err+=dx; y0+=sy

def rings_of(geom):
    if not geom:
        return
    t=geom.get("type")
    c=geom.get("coordinates") or []
    if t=="LineString":
        yield c
    elif t=="MultiLineString":
        for r in c: yield r
    elif t=="Polygon":
        for r in c: yield r
    elif t=="MultiPolygon":
        for poly in c:
            for r in poly: yield r

def feat_bb(feat):
    b=feat.get("bbox")
    if b and len(b)>=4:
        return float(b[0]), float(b[1]), float(b[2]), float(b[3])
    xs=[]; ys=[]
    geom=feat.get("geometry") or {}
    for ring in rings_of(geom):
        for pt in ring:
            if len(pt)>=2:
                xs.append(float(pt[0])); ys.append(float(pt[1]))
    if not xs:
        return None
    return min(xs), min(ys), max(xs), max(ys)

pad_x=(east-west)*0.05
pad_y=(north-south)*0.05
vw, ve = west-pad_x, east+pad_x
vs, vn = south-pad_y, north+pad_y

marks=set()
try:
    data=json.load(open(path, encoding="utf-8"))
except Exception:
    sys.exit(1)
for feat in data.get("features") or []:
    bb=feat_bb(feat)
    if bb:
        minx,miny,maxx,maxy=bb
        if maxx<vw or minx>ve or maxy<vs or miny>vn:
            continue
    geom=feat.get("geometry") or {}
    for ring in rings_of(geom):
        prev=None
        for pt in ring:
            if len(pt)<2:
                prev=None
                continue
            lo, la = float(pt[0]), float(pt[1])
            if prev is not None:
                plo, pla = prev
                if abs(lo-plo)>180:
                    prev=(lo,la)
                    continue
                x0,y0=project(plo, pla)
                x1,y1=project(lo, la)
                if (x0< -2 and x1< -2) or (x0>w+1 and x1>w+1) or (y0< -2 and y1< -2) or (y0>h+1 and y1>h+1):
                    prev=(lo,la)
                    continue
                for x,y in bres(x0,y0,x1,y1):
                    marks.add((x,y))
            prev=(lo,la)

if mode=="cells":
    with open(dest, "w", encoding="utf-8") as fh:
        for x,y in sorted(marks):
            fh.write("%d %d\n" % (x,y))
elif mode=="ppm":
    buf=bytearray(w*h*3)
    for x,y in marks:
        i=(y*w+x)*3
        buf[i]=230; buf[i+1]=230; buf[i+2]=235
    with open(dest, "wb") as fh:
        fh.write(("P6\n%d %d\n255\n" % (w,h)).encode("ascii"))
        fh.write(buf)
else:
    sys.exit(2)
' "$mode" "$dest" "$w" "$h" "$south" "$north" "$west" "$east" "$ADMIN1_GEOJSON"
}

draw_admin1_on_png() {
  local png=$1 south=$2 north=$3 west=$4 east=$5
  local convert_bin ppm overlay
  [[ -f "$png" ]] || return 0
  ensure_admin1_geojson || return 0
  convert_bin=$(radar_convert_bin) || return 0
  local wh
  wh=$("$convert_bin" "$png" -format "%w %h" info: 2>/dev/null) || return 0
  local w h
  w=${wh%% *}; h=${wh##* }
  [[ "$w" =~ ^[0-9]+$ && "$h" =~ ^[0-9]+$ ]] || return 0
  ppm=$(mktemp --suffix=.ppm)
  overlay=$(mktemp --suffix=.png)
  if raster_admin1 ppm "$ppm" "$w" "$h" "$south" "$north" "$west" "$east" \
    && "$convert_bin" "$ppm" -transparent black "$overlay" 2>/dev/null \
    && "$convert_bin" "$png" "$overlay" -compose over -composite "$png" 2>/dev/null; then
    rm -f "$ppm" "$overlay"
    return 0
  fi
  rm -f "$ppm" "$overlay"
  return 0
}

radar_clamp_zoom() {
  local z=${1:-7}
  [[ "$z" =~ ^[0-9]+$ ]] || z=7
  if (( z < RADAR_ZOOM_MIN )); then z=$RADAR_ZOOM_MIN; fi
  if (( z > RADAR_ZOOM_MAX )); then z=$RADAR_ZOOM_MAX; fi
  printf '%s\n' "$z"
}

radar_zoom_for_geo() {
  if [[ -n "${WEATH_RADAR_ZOOM:-}" ]]; then
    radar_clamp_zoom "$WEATH_RADAR_ZOOM"
    return 0
  fi
  python3 -c '
import json,sys
d=json.load(sys.stdin)
print(9 if d.get("precise") else 7)
' 2>/dev/null || echo 7
}

# Map grid that fills the terminal. Override with WEATH_RADAR_COLS / ROWS.
# Prints: cols rows
radar_grid_size() {
  local cols rows tw th
  if [[ -n "${WEATH_RADAR_COLS:-}" && -n "${WEATH_RADAR_ROWS:-}" ]]; then
    printf '%s %s\n' "$WEATH_RADAR_COLS" "$WEATH_RADAR_ROWS"
    return 0
  fi
  if [[ -r /dev/tty ]] && read -r th tw < <(stty size < /dev/tty 2>/dev/null); then
    :
  else
    tw=${COLUMNS:-}
    th=${LINES:-}
    if [[ ! "$tw" =~ ^[1-9][0-9]*$ || ! "$th" =~ ^[1-9][0-9]*$ ]]; then
      tw=$(tput cols 2>/dev/null || true)
      th=$(tput lines 2>/dev/null || true)
    fi
  fi
  [[ "$tw" =~ ^[1-9][0-9]*$ ]] || tw=80
  [[ "$th" =~ ^[1-9][0-9]*$ ]] || th=24

  # Frame is " |" + cells + "|"; keep N/S/W/E labels, legend, and prompt on screen.
  local avail_c avail_r
  avail_c=$((tw - 4))
  avail_r=$((th - 21))
  if (( avail_c < 20 )); then avail_c=20; fi
  if (( avail_c > 220 )); then avail_c=220; fi
  if (( avail_r < 10 )); then avail_r=10; fi
  if (( avail_r > 80 )); then avail_r=80; fi
  cols=$avail_c
  rows=$(( (cols + 1) / 2 ))
  if (( rows > avail_r )); then
    rows=$avail_r
    cols=$((rows * 2))
    if (( cols > avail_c )); then cols=$avail_c; fi
  fi
  if (( cols < 20 )); then cols=20; fi
  if (( rows < 10 )); then rows=10; fi

  if [[ -n "${WEATH_RADAR_COLS:-}" && "$WEATH_RADAR_COLS" =~ ^[1-9][0-9]*$ ]]; then
    cols=$WEATH_RADAR_COLS
  fi
  if [[ -n "${WEATH_RADAR_ROWS:-}" && "$WEATH_RADAR_ROWS" =~ ^[1-9][0-9]*$ ]]; then
    rows=$WEATH_RADAR_ROWS
  fi
  printf '%s %s\n' "$cols" "$rows"
}

# Re-fetch radar at zoom $1 using the last viewed location.
radar_reshow_at_zoom() {
  local z
  z=$(radar_clamp_zoom "${1:-${LAST_RADAR_ZOOM:-${WEATH_RADAR_ZOOM:-7}}}")
  if [[ -z "${LAST_RADAR_LAT:-}" || -z "${LAST_RADAR_LON:-}" ]]; then
    echo "No radar location to zoom."
    return 1
  fi
  LAST_RADAR_CROP_STEPS=0
  show_radar "$LAST_RADAR_LAT" "$LAST_RADAR_LON" "${LAST_RADAR_LABEL:-}" "${LAST_RADAR_BBOX:-}" "$z"
}

# Inner half of a south,north,west,east view (linear lon, mercator lat).
radar_view_inner_half() {
  python3 -c '
import math,sys
s,n,w,e=map(float, sys.argv[1].split(","))
def my(la):
    la=max(-85.05112878, min(85.05112878, float(la)))
    return math.asinh(math.tan(math.radians(la)))
def inv(y):
    return math.degrees(math.atan(math.sinh(y)))
cy=(my(n)+my(s))/2.0
hy=(my(n)-my(s))/4.0
cx=(w+e)/2.0
hw=(e-w)/4.0
print("%.6f,%.6f,%.6f,%.6f" % (inv(cy-hy), inv(cy+hy), cx-hw, cx+hw))
' "$1"
}

radar_crop_center_half() {
  local src=$1 dest=$2
  local conv
  conv=$(radar_convert_bin) || return 1
  [[ -f "$src" ]] || return 1
  "$conv" "$src" +repage -gravity center -crop "50%x50%+0+0" +repage \
    -resize "256x256!" "$dest" 2>/dev/null
}

# Enlarge the center of the current radar picture (same terrain, closer).
radar_zoom_in_view() {
  local z newz
  z=${LAST_RADAR_ZOOM:-${WEATH_RADAR_ZOOM:-7}}
  [[ "$z" =~ ^[0-9]+$ ]] || z=${WEATH_RADAR_ZOOM:-7}
  newz=$(radar_clamp_zoom $((z+1)))
  if (( newz <= z )); then
    echo "Already at max zoom (${RADAR_ZOOM_MAX})."
    return 1
  fi
  if [[ -z "${LAST_RADAR_PNG:-}" || ! -f "$LAST_RADAR_PNG" || -z "${LAST_RADAR_VIEW:-}" ]]; then
    radar_reshow_at_zoom "$newz"
    return
  fi

  local out tmp
  out="$CACHE_DIR/radar_zoom_${newz}_$$.png"
  tmp=$(mktemp --suffix=.png)
  if ! radar_crop_center_half "$LAST_RADAR_PNG" "$tmp"; then
    rm -f "$tmp"
    radar_reshow_at_zoom "$newz"
    return
  fi
  mv "$tmp" "$out"
  for suf in .radar.png .base.png; do
    if [[ -f "${LAST_RADAR_PNG}${suf}" ]]; then
      radar_crop_center_half "${LAST_RADAR_PNG}${suf}" "${out}${suf}" || true
    fi
  done

  LAST_RADAR_VIEW=$(radar_view_inner_half "$LAST_RADAR_VIEW")
  LAST_RADAR_ZOOM=$newz
  LAST_RADAR_PNG=$out
  LAST_RADAR_CROP_STEPS=$((${LAST_RADAR_CROP_STEPS:-0}+1))
  local tx ty
  tx=${LAST_RADAR_TX:-0}; ty=${LAST_RADAR_TY:-0}
  if [[ -n "${LAST_RADAR_LAT:-}" && -n "${LAST_RADAR_LON:-}" ]]; then
    read -r tx ty < <(latlon_to_tile "$LAST_RADAR_LAT" "$LAST_RADAR_LON" "$newz")
    LAST_RADAR_TX=$tx
    LAST_RADAR_TY=$ty
  fi

  echo "${C_BOLD}${C_CYAN}  Radar${C_RESET}  ${C_DIM}${LAST_RADAR_LABEL}  (${LAST_RADAR_LAT}, ${LAST_RADAR_LON})${C_RESET}"
  hr
  echo "${C_DIM}  Zoom in (center of previous view) z=${newz}${C_RESET}"
  local cols rows
  read -r cols rows < <(radar_grid_size)
  render_radar_png "$out" "$cols" "$rows" \
    "${LAST_RADAR_LAT}" "${LAST_RADAR_LON}" "$newz" "$tx" "$ty" \
    "${LAST_RADAR_BBOX}" "${LAST_RADAR_VIEW}" || return 1
  print_radar_legend "$newz" "$tx" "$ty" "${LAST_RADAR_WHEN}" \
    "zoomed center of previous view" \
    "${LAST_RADAR_LAT}" "${LAST_RADAR_LON}" "${LAST_RADAR_BBOX}" "${LAST_RADAR_VIEW}"
}

latlon_to_tile() {
  # args: lat lon zoom → print x y
  python3 -c '
import math,sys
lat=float(sys.argv[1]); lon=float(sys.argv[2]); z=int(sys.argv[3])
n=2**z
x=int((lon+180.0)/360.0*n)
lat_r=math.radians(lat)
y=int((1.0-math.asinh(math.tan(lat_r))/math.pi)/2.0*n)
# clamp
x=max(0,min(n-1,x)); y=max(0,min(n-1,y))
print(x,y)
' "$1" "$2" "$3"
}

radar_convert_bin() {
  if command -v magick >/dev/null 2>&1; then
    echo magick
  elif command -v convert >/dev/null 2>&1; then
    echo convert
  else
    return 1
  fi
}

set_last_radar() {
  LAST_RADAR_PNG=$1
  LAST_RADAR_LABEL=${2:-}
  LAST_RADAR_WHEN=${3:-}
  LAST_RADAR_LAT=${4:-}
  LAST_RADAR_LON=${5:-}
  LAST_RADAR_ZOOM=${6:-}
  LAST_RADAR_TX=${7:-}
  LAST_RADAR_TY=${8:-}
  LAST_RADAR_BBOX=${9:-}
  LAST_RADAR_VIEW=${10:-}
  LAST_RADAR_CROP_STEPS=0
}

# Build a 256x256 view centered on lat/lon: ground basemap + radar overlay.
# Prints: tx ty south north west east
compose_centered_radar() {
  local lat=$1 lon=$2 zoom=$3 host=$4 path=$5 out_png=$6
  local convert_bin
  convert_bin=$(radar_convert_bin) || return 1
  python3 -c '
import math,os,sys,subprocess

lat=float(sys.argv[1]); lon=float(sys.argv[2]); zoom=int(sys.argv[3])
host, path, out_png, cache, ua, conv = sys.argv[4:10]
os.makedirs(cache, exist_ok=True)
n=2**zoom
size=256

def lonlat_to_frac(la, lo):
    la=max(-85.05112878, min(85.05112878, float(la)))
    x=(float(lo)+180.0)/360.0*n
    y=(1.0-math.asinh(math.tan(math.radians(la)))/math.pi)/2.0*n
    return x, y

def frac_to_lonlat(x, y):
    lo=x/n*360.0-180.0
    la=math.degrees(math.atan(math.sinh(math.pi*(1.0-2.0*y/n))))
    return la, lo

def wrap_x(x):
    return int(x) % n

def clamp_y(y):
    return max(0, min(n-1, int(y)))

def fetch(url, dest):
    if os.path.isfile(dest) and os.path.getsize(dest)>80:
        return dest
    part=dest+".part"
    try:
        subprocess.check_call(
            ["curl","-fsSL","--max-time","20","-A",ua,"-o",part,url],
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        if os.path.isfile(part) and os.path.getsize(part)>80:
            os.replace(part, dest)
            return dest
    except Exception:
        pass
    try:
        if os.path.isfile(part):
            os.remove(part)
    except Exception:
        pass
    return None

def blank_tmp(tag):
    dest=os.path.join(cache, "blank_%s_%d.png" % (tag, os.getpid()))
    subprocess.call([conv,"-size","%dx%d"%(size,size),"xc:none",dest],
                    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    return dest

fx, fy = lonlat_to_frac(lat, lon)
left, top = fx-0.5, fy-0.5
tx0=math.floor(left); ty0=math.floor(top)
tx_pt=max(0,min(n-1,int(math.floor(fx))))
ty_pt=max(0,min(n-1,int(math.floor(fy))))

safe=path.strip("/").replace("/","_")
radar_files=[]
base_files=[]
for dy in (0,1):
    for dx in (0,1):
        tx=wrap_x(tx0+dx)
        ty=clamp_y(ty0+dy)
        rf=os.path.join(cache, "rv_%s_%d_%d_%d.png" % (safe, zoom, tx, ty))
        bf=os.path.join(cache, "bm_%d_%d_%d.png" % (zoom, tx, ty))
        rurl="%s%s/%d/%d/%d/%d/2/1_1.png" % (host, path, size, zoom, tx, ty)
        burl="https://a.basemaps.cartocdn.com/dark_all/%d/%d/%d.png" % (zoom, tx, ty)
        got=fetch(rurl, rf)
        radar_files.append(got if got else blank_tmp("r"))
        gotb=fetch(burl, bf)
        if not gotb:
            ourl="https://tile.openstreetmap.org/%d/%d/%d.png" % (zoom, tx, ty)
            gotb=fetch(ourl, bf)
        base_files.append(gotb if gotb else blank_tmp("b"))

def mosaic(files, dest):
    # files: NW, NE, SW, SE. Append stepwise and drop inherited
    # 256x256 page offsets so later -crop uses the full 512x512 raster.
    row0=dest+".row0.png"
    row1=dest+".row1.png"
    ok=(
        subprocess.call([conv, files[0], files[1], "+append", "+repage", row0],
                        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)==0
        and subprocess.call([conv, files[2], files[3], "+append", "+repage", row1],
                        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)==0
        and subprocess.call([conv, row0, row1, "-append", "+repage", dest],
                        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)==0
        and os.path.isfile(dest)
    )
    for p in (row0, row1):
        try: os.remove(p)
        except Exception: pass
    return ok

tmp_r=os.path.join(cache, "mosaic_r_%d.png" % os.getpid())
tmp_b=os.path.join(cache, "mosaic_b_%d.png" % os.getpid())
if not mosaic(radar_files, tmp_r) or not mosaic(base_files, tmp_b):
    sys.exit(1)

# Pixel of the target in the 512 mosaic, then crop so it is dead center.
px=(fx-tx0)*size
py=(fy-ty0)*size
ox=int(round(px-size/2.0))
oy=int(round(py-size/2.0))
ox=max(0, min(size, ox))
oy=max(0, min(size, oy))

crop_r=os.path.join(cache, "crop_r_%d.png" % os.getpid())
crop_b=os.path.join(cache, "crop_b_%d.png" % os.getpid())
for src, dst in ((tmp_r, crop_r), (tmp_b, crop_b)):
    subprocess.call(
        [conv, src, "+repage", "-crop", "%dx%d+%d+%d"%(size,size,ox,oy), "+repage", dst],
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

# Keep radar-only (RGBA) and basemap crops as sidecars so ASCII can
# read precip from alpha. Composite is for export / review only.
radar_side=out_png+".radar.png"
base_side=out_png+".base.png"
subprocess.call([conv, crop_r, radar_side], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Keep basemap in color so water (blue) can be told from land.
subprocess.call([conv, crop_b, "-type", "TrueColor", "png24:"+base_side],
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
r=subprocess.call(
    [conv, crop_b, crop_r, "-compose", "over", "-composite",
     "-background", "#0b1220", "-alpha", "remove", "-alpha", "off",
     "-type", "TrueColor", "png24:"+out_png],
    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for p in (tmp_r, tmp_b, crop_r, crop_b):
    try: os.remove(p)
    except Exception: pass
if r!=0 or not os.path.isfile(out_png) or not os.path.isfile(radar_side):
    sys.exit(1)

# View window is 1.0 tile centered on the point
lat_n, lon_w = frac_to_lonlat(fx-0.5, fy-0.5)
lat_s, lon_e = frac_to_lonlat(fx+0.5, fy+0.5)
print("%d %d %.6f %.6f %.6f %.6f" % (tx_pt, ty_pt, lat_s, lat_n, lon_w, lon_e))
' "$lat" "$lon" "$zoom" "$host" "$path" "$out_png" "$CACHE_DIR" "$USER_AGENT" "$convert_bin"
}

default_radar_export_path() {
  local safe when
  safe=$(python3 -c '
import re,sys
s=sys.argv[1] or "radar"
s=re.sub(r"[^A-Za-z0-9]+", "_", s).strip("_")
print((s or "radar")[:40])
' "${LAST_RADAR_LABEL:-radar}")
  when=$(date -u +%Y%m%dT%H%MZ 2>/dev/null || date +%Y%m%dT%H%M)
  echo "${PWD}/weath-radar-${safe}-${when}.png"
}

# Write a shareable PNG: caption + scaled RainViewer tile.
export_radar_view_png() {
  local src=$1 dest=$2
  local convert_bin
  convert_bin=$(radar_convert_bin) || {
    echo "Error: ImageMagick (convert or magick) required to export PNG." >&2
    return 1
  }
  [[ -f "$src" ]] || {
    echo "Error: radar image not found: $src" >&2
    return 1
  }

  dest=${dest/#\~/$HOME}
  if [[ ! "$dest" =~ \.[Pp][Nn][Gg]$ ]]; then
    dest="${dest}.png"
  fi
  local dest_dir
  dest_dir=$(dirname -- "$dest")
  mkdir -p "$dest_dir" || {
    echo "Error: cannot create directory: $dest_dir" >&2
    return 1
  }

  local map_src="$src" tmpmap=""
  if [[ -n "${LAST_RADAR_VIEW:-}" ]]; then
    tmpmap=$(mktemp --suffix=.png)
    cp -- "$src" "$tmpmap"
    local vs vn vw ve
    vs=${LAST_RADAR_VIEW%%,*}; rest=${LAST_RADAR_VIEW#*,}
    vn=${rest%%,*}; rest=${rest#*,}
    vw=${rest%%,*}; ve=${rest#*,}
    draw_admin1_on_png "$tmpmap" "$vs" "$vn" "$vw" "$ve"
    map_src="$tmpmap"
  fi

  if python3 -c '
import subprocess,sys,os,math
bin,src,dest,label,when,lat,lon,zoom,tx,ty,bbox,view = (sys.argv[1:13]+[""]*12)[:12]
lines=[]
if label: lines.append(label)
if lat or lon: lines.append("%s, %s" % (lat, lon))
if when: lines.append(when)

def tile_bounds(z, x, y):
    n=2**int(z)
    west=x/n*360.0-180.0
    east=(x+1)/n*360.0-180.0
    def y2lat(yy):
        return math.degrees(math.atan(math.sinh(math.pi*(1-2*yy/n))))
    return y2lat(y+1), y2lat(y), west, east

def merc_y(la):
    la=max(-85.05112878, min(85.05112878, float(la)))
    return math.asinh(math.tan(math.radians(la)))

ts=tn=tw=te=None
try:
    parts=(view or "").split(",")
    if len(parts)==4:
        ts,tn,tw,te=map(float, parts)
        lines.append("view N %.3f S %.3f W %.3f E %.3f" % (tn,ts,tw,te))
    elif zoom!="" and tx!="" and ty!="":
        ts,tn,tw,te=tile_bounds(int(zoom), int(tx), int(ty))
        lines.append("tile N %.3f S %.3f W %.3f E %.3f" % (tn,ts,tw,te))
except Exception:
    pass
if bbox:
    parts=bbox.split(",")
    if len(parts)==4:
        try:
            bs,bn,bw,be=map(float, parts)
            lines.append("search N %.3f S %.3f W %.3f E %.3f" % (bn,bs,bw,be))
        except Exception:
            pass
lines.append("Weath / RainViewer + Carto")
caption="\n".join(lines)

tile_cmd=[bin, src, "-resize", "512x512"]
if ts is not None:
    def xy(lo, la):
        fx=(float(lo)-tw)/(te-tw) if te!=tw else 0.5
        mn,ms,my=merc_y(tn),merc_y(ts),merc_y(la)
        fy=(mn-my)/(mn-ms) if mn!=ms else 0.5
        return fx*511.0, fy*511.0
    if bbox:
        parts=bbox.split(",")
        if len(parts)==4:
            try:
                bs,bn,bw,be=map(float, parts)
                bw=min(te, max(tw, bw)); be=min(te, max(tw, be))
                bs=min(tn, max(ts, bs)); bn=min(tn, max(ts, bn))
                x1,y1=xy(bw, bn); x2,y2=xy(be, bs)
                tile_cmd += ["-fill","none","-stroke","#00cccc","-strokewidth","2",
                             "-draw","rectangle %g,%g %g,%g" % (x1,y1,x2,y2)]
            except Exception:
                pass
    if lat!="" and lon!="":
        try:
            if view:
                px,py=255.5, 255.5
            else:
                px,py=xy(lon, lat)
            if 0<=px<=511 and 0<=py<=511:
                tile_cmd += ["-stroke","#ff66cc","-strokewidth","2",
                             "-draw","line %g,%g %g,%g" % (px-10,py,px+10,py),
                             "-draw","line %g,%g %g,%g" % (px,py-10,px,py+10)]
        except Exception:
            pass

cmd=[bin,
     "(", "-background","#111111","-fill","#eeeeee","-pointsize","14",
     "-size","512x96","caption:"+caption, ")",
     "("] + tile_cmd[1:] + [")",
     "-background","#111111","-gravity","center","-append",
     "-bordercolor","#111111","-border","12", dest]
r=subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
sys.exit(0 if r.returncode==0 and os.path.isfile(dest) else 1)
' "$convert_bin" "$map_src" "$dest" \
    "${LAST_RADAR_LABEL:-Radar}" "${LAST_RADAR_WHEN:-}" \
    "${LAST_RADAR_LAT:-}" "${LAST_RADAR_LON:-}" \
    "${LAST_RADAR_ZOOM:-}" "${LAST_RADAR_TX:-}" "${LAST_RADAR_TY:-}" \
    "${LAST_RADAR_BBOX:-}" "${LAST_RADAR_VIEW:-}"; then
    rm -f "$tmpmap"
    return 0
  fi
  if cp -- "$map_src" "$dest"; then
    rm -f "$tmpmap"
    return 0
  fi
  rm -f "$tmpmap"
  echo "Error: failed to write $dest" >&2
  return 1
}

prompt_export_radar() {
  if [[ -z "${LAST_RADAR_PNG:-}" || ! -f "$LAST_RADAR_PNG" ]]; then
    echo "No radar view to export. Show radar first."
    return 1
  fi
  local default dest
  default=$(default_radar_export_path)
  read -r -p "Export PNG path [${default}]: " dest || return 1
  dest=${dest:-$default}
  dest=${dest/#\~/$HOME}
  if export_radar_view_png "$LAST_RADAR_PNG" "$dest"; then
    if [[ ! "$dest" =~ \.[Pp][Nn][Gg]$ ]]; then
      dest="${dest}.png"
    fi
    echo "Saved: $dest"
    return 0
  fi
  return 1
}

radar_read_key() {
  # $1 = timeout seconds (empty = wait). Prints UP DOWN LEFT RIGHT SPACE ENTER
  # TIMEOUT ESC EOF or a single character.
  local timeout=${1:-} k rest
  if [[ -n "$timeout" ]]; then
    if ! IFS= read -r -s -n 1 -t "$timeout" k; then
      echo TIMEOUT
      return 0
    fi
  else
    if ! IFS= read -r -s -n 1 k; then
      echo EOF
      return 0
    fi
  fi
  if [[ "$k" == $'\x1b' ]]; then
    IFS= read -r -s -n 1 -t 0.05 rest || { echo ESC; return 0; }
    if [[ "$rest" == "[" ]]; then
      IFS= read -r -s -n 1 -t 0.05 rest || { echo ESC; return 0; }
      case "$rest" in
        A) echo UP ;;
        B) echo DOWN ;;
        C) echo RIGHT ;;
        D) echo LEFT ;;
        5)
          IFS= read -r -s -n 1 -t 0.05 _ || true
          echo PGUP
          ;;
        6)
          IFS= read -r -s -n 1 -t 0.05 _ || true
          echo PGDN
          ;;
        *) echo ESC ;;
      esac
    else
      echo ESC
    fi
  elif [[ -z "$k" || "$k" == $'\n' || "$k" == $'\r' ]]; then
    echo ENTER
  elif [[ "$k" == " " ]]; then
    echo SPACE
  else
    printf '%s\n' "$k"
  fi
}

radar_auto_arm() {
  LAST_RADAR_AUTO_NEXT=$(( $(date +%s) + RADAR_AUTO_SEC ))
}

radar_auto_remaining() {
  if [[ "${LAST_RADAR_AUTO:-0}" != "1" ]]; then
    echo ""
    return 0
  fi
  local now rem
  now=$(date +%s)
  rem=$((LAST_RADAR_AUTO_NEXT - now))
  if (( rem < 1 )); then rem=1; fi
  echo "$rem"
}

radar_pick_past_frames() {
  # stdin: weather-maps.json  args: lookback_minutes
  # prints: epoch<TAB>path
  python3 -c '
import json,sys
look=int(sys.argv[1])
d=json.load(sys.stdin)
past=d.get("radar",{}).get("past") or []
if not past:
    sys.exit(1)
latest=int(past[-1]["time"])
cut=latest - look*60
frames=[p for p in past if int(p.get("time") or 0) >= cut]
if len(frames)<2 and len(past)>=2:
    frames=past[-2:]
for p in frames:
    print("%s\t%s" % (p["time"], p["path"]))
' "$1"
}

radar_update_current() {
  if [[ -z "${LAST_RADAR_LAT:-}" || -z "${LAST_RADAR_LON:-}" ]]; then
    echo "No radar location to update."
    return 1
  fi
  echo "${C_DIM}Updating to current radar...${C_RESET}"
  radar_reshow_at_zoom "${LAST_RADAR_ZOOM:-${WEATH_RADAR_ZOOM:-7}}"
  radar_auto_arm
}

radar_toggle_auto() {
  local quiet=${1:-}
  if [[ "${LAST_RADAR_AUTO:-0}" == "1" ]]; then
    LAST_RADAR_AUTO=0
    [[ -n "$quiet" ]] || echo "Auto update: off"
  else
    LAST_RADAR_AUTO=1
    radar_auto_arm
    [[ -n "$quiet" ]] || echo "Auto update: on (every 5 min). Press A to turn off."
  fi
}

radar_export_anim_gif() {
  # Uses $1 = built.tsv (epoch when png txt), $2 = dest gif, $3 = sec/frame
  local tsv=$1 dest=$2 sec=${3:-2} label=${4:-}
  local convert_bin
  convert_bin=$(radar_convert_bin) || {
    echo "Error: ImageMagick required to write GIF." >&2
    return 1
  }
  dest=${dest/#\~/$HOME}
  if [[ ! "$dest" =~ \.[Gg][Ii][Ff]$ ]]; then
    dest="${dest}.gif"
  fi
  mkdir -p "$(dirname -- "$dest")" || return 1
  python3 -c '
import subprocess,sys,os,re

tsv, dest, sec, label, vendor, app, conv = sys.argv[1:8]
try:
    delay=int(float(sec)*100)
except Exception:
    delay=200
if delay<20: delay=20
rows=[]
with open(tsv, encoding="utf-8") as fh:
    for ln in fh:
        ln=ln.strip()
        if not ln: continue
        parts=ln.split("\t")
        if len(parts)>=3 and os.path.isfile(parts[2]):
            rows.append((parts[1] if len(parts)>1 else "", parts[2]))
if not rows:
    sys.exit(1)
work=os.path.join(os.path.dirname(rows[0][1]), "gifwork")
os.makedirs(work, exist_ok=True)
titled=[]
for i,(when, png) in enumerate(rows, 1):
    cap="\n".join([
        app,
        vendor,
        label or "Radar",
        when or "",
    ])
    out=os.path.join(work, "t%03d.png" % i)
    cmd=[conv,
         "(", "-background","#0b1220","-fill","#f2f2f2","-pointsize","18",
         "-size","512x88","caption:"+cap, ")",
         "(", png, "-resize","512x512", ")",
         "-background","#0b1220","-gravity","center","-append",
         "-bordercolor","#0b1220","-border","10", out]
    r=subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    if r.returncode!=0 or not os.path.isfile(out):
        sys.exit(1)
    titled.append(out)
gifcmd=[conv, "-delay", str(delay), "-loop", "0"] + titled + [dest]
r=subprocess.run(gifcmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for p in titled:
    try: os.remove(p)
    except Exception: pass
try: os.rmdir(work)
except Exception: pass
sys.exit(0 if r.returncode==0 and os.path.isfile(dest) else 1)
' "$tsv" "$dest" "$sec" "$label" "$APP_VENDOR" "$APP_NAME" "$convert_bin" || return 1
  echo "Saved GIF: $dest"
}

# Build ASCII frames for lookback; play in place with space/arrows/U/A.
radar_animate() {
  local look=${1:-} speed=${2:-}
  if [[ -z "${LAST_RADAR_LAT:-}" || -z "${LAST_RADAR_LON:-}" ]]; then
    echo "Show radar for a location first."
    return 1
  fi
  if [[ -z "$look" ]]; then
    echo "Radar animation"
    echo "Lookback minutes: 1  3  5  10  15  30  60 (1 hour)"
    echo -n "Lookback: "
    read -r look || return 1
  fi
  case "$look" in
    1|3|5|10|15|30|60) ;;
    1h|1hr|60m|hr) look=60 ;;
    "") look=30 ;;
    *)
      echo "Use 1, 3, 5, 10, 15, 30, or 60."
      return 1
      ;;
  esac
  if [[ -z "$speed" ]]; then
    echo -n "Seconds per frame (1, 2, or 3): "
    read -r speed || return 1
  fi
  case "$speed" in
    1|2|3) ;;
    "") speed=2 ;;
    *)
      echo "Use 1, 2, or 3 seconds."
      return 1
      ;;
  esac
  local save_gif="" gif_dest=""
  echo -n "Save animated GIF when frames are ready? [y/N] "
  read -r save_gif || true

  local lat lon zoom bbox view label cols rows
  lat=$LAST_RADAR_LAT
  lon=$LAST_RADAR_LON
  zoom=$(radar_clamp_zoom "${LAST_RADAR_ZOOM:-${WEATH_RADAR_ZOOM:-7}}")
  bbox=${LAST_RADAR_BBOX:-}
  view=${LAST_RADAR_VIEW:-}
  label=${LAST_RADAR_LABEL:-}
  read -r cols rows < <(radar_grid_size)

  local adir
  adir=$(mktemp -d "$CACHE_DIR/anim.XXXXXX")
  RADAR_ANIM_DIR=$adir
  radar_animate_cleanup() {
    tput cnorm 2>/dev/null || true
    [[ -n "${RADAR_ANIM_DIR:-}" && -d "$RADAR_ANIM_DIR" ]] && rm -rf "$RADAR_ANIM_DIR"
    RADAR_ANIM_DIR=""
    trap - RETURN INT
  }
  trap radar_animate_cleanup RETURN INT

  radar_anim_build() {
    local meta host flist n i epoch path png when txt
    echo "${C_DIM}Fetching radar timeline...${C_RESET}"
    meta=$(http_get "https://api.rainviewer.com/public/weather-maps.json") || {
      echo "Error: could not reach RainViewer."
      return 1
    }
    host=$(python3 -c 'import json,sys; print(json.load(sys.stdin)["host"])' <<<"$meta")
    flist="$adir/list.tsv"
    radar_pick_past_frames "$look" <<<"$meta" > "$flist" || {
      echo "No radar frames in that lookback."
      return 1
    }
    n=$(grep -c . "$flist" || echo 0)
    if [[ "$n" -lt 1 ]]; then
      echo "No radar frames in that lookback."
      return 1
    fi
    echo "${C_DIM}RainViewer steps are about 10 min. Building $n frame(s) for ${look} min...${C_RESET}"
    i=0
    : > "$adir/built.tsv"
    while IFS=$'\t' read -r epoch path; do
      [[ -n "$epoch" && -n "$path" ]] || continue
      i=$((i+1))
      printf '\r  Building frame %d/%d   ' "$i" "$n"
      png="$adir/f${i}.png"
      txt="$adir/f${i}.txt"
      if ! read -r tx ty south north west east < <(compose_centered_radar "$lat" "$lon" "$zoom" "$host" "$path" "$png"); then
        echo
        echo "Error: failed to build frame $i."
        return 1
      fi
      view="${south},${north},${west},${east}"
      draw_admin1_on_png "$png" "$south" "$north" "$west" "$east"
      when=$(python3 -c 'import datetime,sys; print(datetime.datetime.fromtimestamp(int(sys.argv[1]), datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC"))' "$epoch" 2>/dev/null || echo "$epoch")
      render_radar_png "$png" "$cols" "$rows" "$lat" "$lon" "$zoom" "$tx" "$ty" "$bbox" "$view" > "$txt" || return 1
      printf '%s\t%s\t%s\t%s\n' "$epoch" "$when" "$png" "$txt" >> "$adir/built.tsv"
    done < "$flist"
    echo
    [[ -s "$adir/built.tsv" ]] || return 1
    LAST_RADAR_VIEW=$view
    LAST_RADAR_TX=${tx:-$LAST_RADAR_TX}
    LAST_RADAR_TY=${ty:-$LAST_RADAR_TY}
  }

  radar_anim_build || return 1

  if [[ "$save_gif" == [yY]* ]]; then
    gif_dest=$(default_radar_export_path)
    gif_dest="${gif_dest%.png}-${look}min.gif"
    echo -n "GIF path [${gif_dest}]: "
    read -r ans || true
    [[ -n "${ans:-}" ]] && gif_dest=$ans
    radar_export_anim_gif "$adir/built.tsv" "$gif_dest" "$speed" "$label" || echo "GIF export failed."
  fi

  local n idx playing nlines status_h
  n=$(grep -c . "$adir/built.tsv")
  idx=$((n-1))
  playing=1
  status_h=2

  radar_anim_field() {
    python3 -c '
import sys
rows=open(sys.argv[1],encoding="utf-8").read().splitlines()
i=int(sys.argv[2]); f=int(sys.argv[3])
if 0<=i<len(rows):
    parts=rows[i].split("\t")
    if 0<=f<len(parts):
        print(parts[f])
' "$adir/built.tsv" "$1" "$2"
  }

  radar_anim_draw() {
    local when png txt auto_s play_s
    when=$(radar_anim_field "$idx" 1)
    png=$(radar_anim_field "$idx" 2)
    txt=$(radar_anim_field "$idx" 3)
    [[ -f "$txt" ]] || return 1
    LAST_RADAR_PNG=$png
    LAST_RADAR_WHEN=$when
    if [[ "$playing" == "1" ]]; then play_s="play  "; else play_s="paused"; fi
    if [[ "${LAST_RADAR_AUTO:-0}" == "1" ]]; then auto_s="auto-on "; else auto_s="auto-off"; fi
    printf '  %s  %d/%d  %s  %s  space pause  arrows step  U update  A auto  g GIF  q stop\n' \
      "$when" "$((idx+1))" "$n" "$play_s" "$auto_s"
    echo "${C_DIM}  Lookback ${look} min   ${speed}s/frame   z=${zoom}${C_RESET}"
    cat "$txt"
    if [[ -z "${nlines:-}" ]]; then
      nlines=$(wc -l < "$txt")
    fi
  }

  radar_anim_redraw() {
    # Move to the top of the previous frame block and replace it.
    if [[ -n "${nlines:-}" ]]; then
      printf '\033[%dA\033[J' "$((nlines + status_h))"
    fi
    radar_anim_draw
  }

  tput civis 2>/dev/null || true
  echo
  echo "${C_BOLD}Radar animation${C_RESET}  ${C_DIM}${label}${C_RESET}"
  radar_anim_draw

  local key rem fdelay
  while true; do
    rem=$(radar_auto_remaining)
    if [[ "$playing" == "1" ]]; then
      fdelay=$speed
    else
      fdelay=""
    fi
    if [[ -n "$rem" ]]; then
      if [[ -n "$fdelay" && "$rem" -lt "$fdelay" ]]; then
        fdelay=$rem
      elif [[ -z "$fdelay" ]]; then
        fdelay=$rem
      fi
    fi
    key=$(radar_read_key "$fdelay")
    case "$key" in
      TIMEOUT)
        if [[ "${LAST_RADAR_AUTO:-0}" == "1" ]]; then
          now=$(date +%s)
          if (( now >= LAST_RADAR_AUTO_NEXT )); then
            echo
            echo "${C_DIM}Auto update...${C_RESET}"
            if radar_anim_build; then
              n=$(grep -c . "$adir/built.tsv")
              idx=$((n-1))
              nlines=""
              radar_auto_arm
              radar_anim_draw
            fi
            continue
          fi
        fi
        if [[ "$playing" == "1" ]]; then
          idx=$((idx+1))
          if (( idx >= n )); then idx=0; fi
          radar_anim_redraw
        fi
        ;;
      SPACE)
        if [[ "$playing" == "1" ]]; then playing=0; else playing=1; fi
        radar_anim_redraw
        ;;
      LEFT|UP)
        playing=0
        idx=$((idx-1))
        if (( idx < 0 )); then idx=$((n-1)); fi
        radar_anim_redraw
        ;;
      RIGHT|DOWN)
        playing=0
        idx=$((idx+1))
        if (( idx >= n )); then idx=0; fi
        radar_anim_redraw
        ;;
      u|U)
        echo
        echo "${C_DIM}Updating frames...${C_RESET}"
        if radar_anim_build; then
          n=$(grep -c . "$adir/built.tsv")
          idx=$((n-1))
          nlines=""
          radar_auto_arm
          radar_anim_draw
        fi
        ;;
      a|A)
        radar_toggle_auto quiet
        radar_anim_redraw
        ;;
      g|G)
        gif_dest=$(default_radar_export_path)
        gif_dest="${gif_dest%.png}-${look}min.gif"
        echo
        echo -n "GIF path [${gif_dest}]: "
        tput cnorm 2>/dev/null || true
        read -r ans || true
        tput civis 2>/dev/null || true
        [[ -n "${ans:-}" ]] && gif_dest=$ans
        radar_export_anim_gif "$adir/built.tsv" "$gif_dest" "$speed" "$label" || echo "GIF export failed."
        nlines=""
        radar_anim_draw
        ;;
      q|Q|ESC|EOF)
        break
        ;;
    esac
  done
  echo
  tput cnorm 2>/dev/null || true
}

# After a radar view: zoom, animate, update, auto, export.
after_radar_view() {
  [[ -t 0 ]] || return 0
  local leave="return to the menu"
  if [[ "${WEATH_MENU:-0}" != "1" ]]; then
    leave="exit"
  fi
  local k cur new rem auto_s
  while true; do
    if [[ "${LAST_RADAR_AUTO:-0}" == "1" ]]; then auto_s="A auto-on"; else auto_s="A auto-off"; fi
    echo
    echo -n "+ zoom in  - zoom out  m movie  g GIF  U update  ${auto_s}  e export  q ${leave}: "
    rem=$(radar_auto_remaining)
    k=$(radar_read_key "$rem")
    echo
    case "$k" in
      TIMEOUT)
        echo "${C_DIM}Auto update (5 min)...${C_RESET}"
        radar_update_current || echo "Update failed."
        ;;
      +|=)
        cur=${LAST_RADAR_ZOOM:-${WEATH_RADAR_ZOOM:-7}}
        [[ "$cur" =~ ^[0-9]+$ ]] || cur=${WEATH_RADAR_ZOOM:-7}
        new=$((cur+1))
        if (( new > RADAR_ZOOM_MAX )); then
          echo "Already at max zoom (${RADAR_ZOOM_MAX})."
          continue
        fi
        echo "${C_DIM}Zoom in (center of current view)...${C_RESET}"
        radar_zoom_in_view || echo "Could not zoom in."
        ;;
      -|_)
        cur=${LAST_RADAR_ZOOM:-${WEATH_RADAR_ZOOM:-7}}
        [[ "$cur" =~ ^[0-9]+$ ]] || cur=${WEATH_RADAR_ZOOM:-7}
        new=$((cur-1))
        if (( new < RADAR_ZOOM_MIN )); then
          echo "Already at min zoom (${RADAR_ZOOM_MIN})."
          continue
        fi
        echo "${C_DIM}Zoom out to ${new}...${C_RESET}"
        radar_reshow_at_zoom "$new" || echo "Could not zoom out."
        ;;
      m|M)
        radar_animate || true
        ;;
      g|G)
        radar_animate || true
        ;;
      u|U)
        radar_update_current || echo "Update failed."
        ;;
      a|A)
        radar_toggle_auto
        ;;
      e|E)
        if [[ -n "${LAST_RADAR_PNG:-}" && -f "$LAST_RADAR_PNG" ]]; then
          prompt_export_radar || true
        else
          echo "No radar view to export."
        fi
        ;;
      q|Q|ENTER|ESC|EOF)
        return 0
        ;;
      *)
        return 0
        ;;
    esac
  done
}

print_radar_legend() {
  local zoom=$1 tx=$2 ty=$3 when=$4 note=${5:-} lat=${6:-} lon=${7:-} bbox=${8:-} view=${9:-}
  echo
  echo -n "  ${C_DIM}Legend intensity:${C_RESET} "
  echo -n "${C_WHITE}${RADAR_CHAR}${C_RESET} light  "
  echo -n "${C_YEL_BRIGHT}${RADAR_CHAR}${C_RESET}${C_YELLOW}${RADAR_CHAR}${C_RESET} mod  "
  echo -n "${C_ORANGE}${RADAR_CHAR}${C_RESET}${C_RED_BRIGHT}${RADAR_CHAR}${C_RESET} heavy  "
  echo "${C_RED}${C_BOLD}${RADAR_CHAR}${C_RESET} extreme"
  echo "  ${C_CYAN}+ - |${C_RESET} search area   ${C_MAGENTA}*${C_RESET} looked-up point   ${C_WHITE}#${C_RESET} state/province"
  echo "  ${C_DIM}. land (no echo)   ${C_CYAN}~${C_RESET} lake / ocean${C_RESET}"
  python3 -c '
import math,sys
zoom,tx,ty,lat,lon,bbox,view = (sys.argv[1:8]+[""]*7)[:7]

def tile_bounds(z, x, y):
    n=2**int(z)
    west=x/n*360.0-180.0
    east=(x+1)/n*360.0-180.0
    def y2lat(yy):
        return math.degrees(math.atan(math.sinh(math.pi*(1-2*yy/n))))
    return y2lat(y+1), y2lat(y), west, east

def hav_mi(lat1, lon1, lat2, lon2):
    R=3958.8
    p1,p2=math.radians(lat1),math.radians(lat2)
    dph=math.radians(lat2-lat1)
    dl=math.radians(lon2-lon1)
    a=math.sin(dph/2)**2+math.cos(p1)*math.cos(p2)*math.sin(dl/2)**2
    return 2*R*math.asin(min(1.0, math.sqrt(a)))

try:
    parts=(view or "").split(",")
    if len(parts)==4:
        ts,tn,tw,te=map(float, parts)
        kind="view"
    else:
        ts,tn,tw,te=tile_bounds(int(zoom), int(tx), int(ty))
        kind="tile"
    ew=hav_mi((tn+ts)/2, tw, (tn+ts)/2, te)
    ns=hav_mi(tn, (tw+te)/2, ts, (tw+te)/2)
    print("  %s (centered): N %.4f  S %.4f  W %.4f  E %.4f" % (kind, tn,ts,tw,te))
    print("  %s size: %.0f mi W-E  x  %.0f mi N-S   z=%s" % (kind, ew, ns, zoom))
except Exception:
    print("  tile z=%s (%s,%s)" % (zoom, tx, ty))
if bbox:
    parts=bbox.split(",")
    if len(parts)==4:
        try:
            bs,bn,bw,be=map(float, parts)
            ew=hav_mi((bn+bs)/2, bw, (bn+bs)/2, be)
            ns=hav_mi(bn, (bw+be)/2, bs, (bw+be)/2)
            print("  search boundary: N %.4f  S %.4f  W %.4f  E %.4f" % (bn,bs,bw,be))
            print("  search size: %.1f mi W-E  x  %.1f mi N-S" % (ew, ns))
        except Exception:
            pass
if lat and lon:
    print("  looked-up point: %s, %s" % (lat, lon))
' "$zoom" "$tx" "$ty" "$lat" "$lon" "$bbox" "$view"
  echo "  ${C_DIM}+ zoom in   - zoom out   (z ${zoom}, range ${RADAR_ZOOM_MIN}-${RADAR_ZOOM_MAX})${C_RESET}"
  echo "  ${C_DIM}frame ${when}  -  source: RainViewer  -  glyph: ASCII 254 (${RADAR_CHAR})${C_RESET}"
  if [[ -n "$note" ]]; then
    echo "  ${C_DIM}${note}${C_RESET}"
  fi
  echo
}

# Render a local radar PNG to the terminal. No network.
# Optional args 4-10: lat lon zoom tx ty bbox view(south,north,west,east)
render_radar_png() {
  local tile_png=$1
  local cols=$2
  local rows=$3
  local lat=${4:-} lon=${5:-} zoom=${6:-} tx=${7:-} ty=${8:-} bbox=${9:-} view=${10:-}
  local convert_bin
  convert_bin=$(radar_convert_bin) || {
    echo "Error: ImageMagick (convert or magick) required for radar." >&2
    return 1
  }
  [[ -f "$tile_png" ]] || {
    echo "Error: radar image not found: $tile_png" >&2
    return 1
  }

  local radar_src="$tile_png"
  local base_src=""
  if [[ -f "${tile_png}.radar.png" ]]; then
    radar_src="${tile_png}.radar.png"
  fi
  if [[ -f "${tile_png}.base.png" ]]; then
    base_src="${tile_png}.base.png"
  fi

  local base_txt=""
  if [[ -n "$base_src" && -f "$base_src" ]]; then
    base_txt=$(mktemp)
    "$convert_bin" "$base_src" -resize "${cols}x${rows}!" txt:- >"$base_txt" 2>/dev/null || true
  fi

  local admin_cells=""
  local water_cells=""
  if [[ -n "$view" ]]; then
    local vs vn vw ve
    vs=${view%%,*}; rest=${view#*,}
    vn=${rest%%,*}; rest=${rest#*,}
    vw=${rest%%,*}; ve=${rest#*,}
    if [[ -n "$vs" && -n "$ve" ]]; then
      ensure_admin1_geojson || true
      admin_cells=$(mktemp)
      raster_admin1 cells "$admin_cells" "$cols" "$rows" "$vs" "$vn" "$vw" "$ve" || true
      ensure_water_geojson || true
      water_cells=$(mktemp)
      raster_water "$water_cells" "$cols" "$rows" "$vs" "$vn" "$vw" "$ve" || true
    fi
  fi

  # Sample radar (RGBA alpha) separately from the ground basemap.
  "$convert_bin" "$radar_src" -resize "${cols}x${rows}!" txt:- 2>/dev/null | WEATH_RADAR_BASE_TXT="$base_txt" WEATH_ADMIN1_CELLS="$admin_cells" WEATH_WATER_CELLS="$water_cells" python3 -c '
import sys,re,math,os

cols=int(sys.argv[1]); rows=int(sys.argv[2]); ch=sys.argv[3]
lat,lon,zoom,tx,ty,bbox,view,base_src = (sys.argv[4:12] + [""]*8)[:8]
# Parse ImageMagick txt
# 0,0: (r,g,b,a) or (r,g,b)
pat=re.compile(r"^(\d+),(\d+): \(([^)]+)\)")

def parse_txt(stream, cols, rows):
    rgba=[[(0,0,0,0)]*cols for _ in range(rows)]
    for line in stream:
        m=pat.match(line.strip())
        if not m: continue
        x,y=int(m.group(1)), int(m.group(2))
        if x>=cols or y>=rows: continue
        parts=[p.strip() for p in m.group(3).split(",")]
        try:
            nums=[]
            for p in parts[:4]:
                p=p.replace("%","")
                nums.append(float(p))
        except Exception:
            continue
        if len(nums)>=4:
            r,g,b,a=nums[:4]
            if r>255 or g>255 or b>255 or a>255:
                r,g,b,a=r/257,g/257,b/257,a/257
        elif len(nums)==3:
            r,g,b=nums; a=255.0 if (r+g+b)>0 else 0.0
        elif len(nums)==1:
            # ImageMagick gray(): Carto dark_all tiles are grayscale.
            r=g=b=nums[0]
            if r>255:
                r=g=b=r/257.0
            a=255.0
        else:
            continue
        rgba[y][x]=(r,g,b,a)
    return rgba

radar=parse_txt(sys.stdin, cols, rows)
water=[[0]*cols for _ in range(rows)]
water_cells=os.environ.get("WEATH_WATER_CELLS","")
if water_cells and os.path.isfile(water_cells):
    try:
        with open(water_cells, encoding="utf-8") as fh:
            for line in fh:
                parts=line.split()
                if len(parts)<2: continue
                try:
                    wx,wy=int(parts[0]), int(parts[1])
                except Exception:
                    continue
                if 0<=wx<cols and 0<=wy<rows:
                    water[wy][wx]=1
    except Exception:
        pass
have_geo=bool(water_cells and os.path.isfile(water_cells))
base_txt=os.environ.get("WEATH_RADAR_BASE_TXT","")
if base_txt and os.path.isfile(base_txt):
    with open(base_txt, encoding="utf-8", errors="replace") as fh:
        bpx=parse_txt(fh, cols, rows)
    for y in range(rows):
        for x in range(cols):
            if water[y][x]:
                continue
            r,g,b,a=bpx[y][x]
            if a < 8:
                continue
            # OSM / light tiles: water is blue-dominant.
            if (b > r + 16 and b > g + 6) or (b > r + 8 and b > g + 8 and (0.25*r+0.45*g+0.30*b) < 40):
                water[y][x]=1
                continue
            # Carto dark_all is gray (no blue). Only use darkness when
            # the lake/ocean polygons were not available.
            if not have_geo:
                chroma=max(r,g,b)-min(r,g,b)
                lum=(r+g+b)/3.0
                if chroma < 10 and 1.0 < lum <= 20.0:
                    water[y][x]=1

grid=[[0]*cols for _ in range(rows)]
for y in range(rows):
    for x in range(cols):
        r,g,b,a=radar[y][x]
        if a < 8:
            inten=0
        else:
            bright=(0.25*r + 0.45*g + 0.30*b) * (a/255.0)
            if r > g and r > 100:
                bright += 40
            if r > 200 and g < 100:
                bright += 50
            inten=bright
        grid[y][x]=inten

vals=sorted(v for row in grid for v in row if v>0)
def level(v):
    if v<=0: return 0
    if not vals: return 1
    if v < 25: return 1
    if v < 50: return 2
    if v < 80: return 3
    if v < 120: return 4
    if v < 170: return 5
    return 6

colors=[
  "\033[38;5;236m",
  "\033[97m",
  "\033[93m",
  "\033[33m",
  "\033[38;5;208m",
  "\033[91m",
  "\033[31;1m",
]
reset="\033[0m"
cyan="\033[36;1m"
mag="\033[35;1m"

def tile_bounds(z, x, y):
    n=2**int(z)
    west=x/n*360.0-180.0
    east=(x+1)/n*360.0-180.0
    def y2lat(yy):
        return math.degrees(math.atan(math.sinh(math.pi*(1-2*yy/n))))
    return y2lat(y+1), y2lat(y), west, east

overlay=[[None]*cols for _ in range(rows)]
border="\033[97m"
admin_cells=os.environ.get("WEATH_ADMIN1_CELLS","")
if admin_cells and os.path.isfile(admin_cells):
    try:
        with open(admin_cells, encoding="utf-8") as fh:
            for line in fh:
                parts=line.split()
                if len(parts)<2: continue
                try:
                    ax,ay=int(parts[0]), int(parts[1])
                except Exception:
                    continue
                if 0<=ax<cols and 0<=ay<rows:
                    overlay[ay][ax]=("#", border)
    except Exception:
        pass
ts=tn=tw=te=None
try:
    parts=(view or "").split(",")
    if len(parts)==4:
        ts,tn,tw,te=map(float, parts)
    elif zoom!="" and tx!="" and ty!="":
        ts,tn,tw,te=tile_bounds(int(zoom), int(tx), int(ty))
except Exception:
    ts=None

def merc_y(la):
    la=max(-85.05112878, min(85.05112878, float(la)))
    return math.asinh(math.tan(math.radians(la)))

def lonlat_xy(lo, la):
    if ts is None or te==tw or tn==ts:
        return None
    fx=(float(lo)-tw)/(te-tw)
    mn,ms,my=merc_y(tn),merc_y(ts),merc_y(la)
    fy=(mn-my)/(mn-ms) if mn!=ms else 0.5
    x=int(round(fx*(cols-1)))
    y=int(round(fy*(rows-1)))
    if x<0 or x>=cols or y<0 or y>=rows:
        return None
    return x,y

def draw_rect(x1,y1,x2,y2):
    if x1>x2: x1,x2=x2,x1
    if y1>y2: y1,y2=y2,y1
    if x2==x1:
        x2=min(cols-1, x1+1)
    if y2==y1:
        y2=min(rows-1, y1+1)
    for x in range(x1, x2+1):
        overlay[y1][x]=("-", cyan)
        overlay[y2][x]=("-", cyan)
    for y in range(y1, y2+1):
        overlay[y][x1]=("|", cyan)
        overlay[y][x2]=("|", cyan)
    overlay[y1][x1]=("+", cyan)
    overlay[y1][x2]=("+", cyan)
    overlay[y2][x1]=("+", cyan)
    overlay[y2][x2]=("+", cyan)

if ts is not None and bbox:
    parts=bbox.split(",")
    if len(parts)==4:
        try:
            bs,bn,bw,be=map(float, parts)
            if not (be<tw or bw>te or bn<ts or bs>tn):
                bw=min(te, max(tw, bw)); be=min(te, max(tw, be))
                bs=min(tn, max(ts, bs)); bn=min(tn, max(ts, bn))
                p1=lonlat_xy(bw, bn)
                p2=lonlat_xy(be, bs)
                if p1 and p2:
                    draw_rect(p1[0], p1[1], p2[0], p2[1])
        except Exception:
            pass

if lat!="" and lon!="":
    try:
        # Mark the looked-up point, not the frame center, so an address
        # stays on the house/POI even if the view is a larger area.
        pt=lonlat_xy(lon, lat)
        if pt:
            overlay[pt[1]][pt[0]]=("*", mag)
        elif view:
            overlay[rows//2][cols//2]=("*", mag)
    except Exception:
        pass

frame_w=cols+2
if tn is not None:
    nlab="N %.3f" % tn
    print(" "+nlab.center(frame_w))
print(" +"+("-"*cols)+"+")
for y in range(rows):
    line=[" |"]
    for x in range(cols):
        ov=overlay[y][x]
        if ov:
            c,col=ov
            line.append(col+c+reset)
        else:
            lv=level(grid[y][x])
            if lv>0:
                line.append(colors[lv]+ch+reset)
            elif water[y][x]:
                line.append("\033[36m~"+reset)
            else:
                line.append("\033[38;5;245m."+reset)
    line.append("|")
    print("".join(line))
print(" +"+("-"*cols)+"+")
if ts is not None:
    slab="S %.3f" % ts
    print(" "+slab.center(frame_w))
    left="W %.3f" % tw
    right="E %.3f" % te
    pad=frame_w - len(left) - len(right)
    print(" "+left+(" "*max(1,pad))+right)
' "$cols" "$rows" "$RADAR_CHAR" "$lat" "$lon" "$zoom" "$tx" "$ty" "$bbox" "$view"
  rm -f "$base_txt" "$admin_cells" "$water_cells"
}

# Archive a fetched radar tile. Keeps the newest MAX_RADAR_HISTORY entries.
save_radar_snapshot() {
  local tile_png=$1
  local meta_json=$2
  python3 -c '
import json,sys,os,shutil,datetime

hist_path, frames_dir, last_path, src_png = sys.argv[1:5]
max_h = int(sys.argv[5])
rec = json.load(sys.stdin)
if not os.path.isfile(src_png):
    sys.exit(1)

os.makedirs(frames_dir, exist_ok=True)
os.makedirs(os.path.dirname(hist_path) or ".", exist_ok=True)

stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
rid = "%s_%s_%s_%s" % (stamp, rec.get("zoom",""), rec.get("tx",""), rec.get("ty",""))
dest_name = rid + ".png"
dest = os.path.join(frames_dir, dest_name)
if os.path.exists(dest):
    rid = rid + "_" + str(os.getpid())
    dest_name = rid + ".png"
    dest = os.path.join(frames_dir, dest_name)
shutil.copy2(src_png, dest)
for suf in (".radar.png", ".base.png"):
    side=src_png+suf
    if os.path.isfile(side):
        shutil.copy2(side, dest+suf)

rec["id"] = rid
rec["png"] = "frames/" + dest_name
if not rec.get("fetched_at"):
    rec["fetched_at"] = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

with open(hist_path, "a", encoding="utf-8") as f:
    f.write(json.dumps(rec, ensure_ascii=False) + "\n")

try:
    with open(hist_path, encoding="utf-8") as f:
        lines = [ln for ln in f if ln.strip()]
    if len(lines) > max_h:
        dropped, keep = lines[:-max_h], lines[-max_h:]
        for ln in dropped:
            try:
                old = json.loads(ln)
                rel = old.get("png") or ""
                if rel:
                    old_png = rel if os.path.isabs(rel) else os.path.join(os.path.dirname(hist_path), rel)
                    if os.path.isfile(old_png):
                        os.remove(old_png)
                    for suf in (".radar.png", ".base.png"):
                        if os.path.isfile(old_png+suf):
                            os.remove(old_png+suf)
            except Exception:
                pass
        with open(hist_path, "w", encoding="utf-8") as f:
            f.writelines(keep)
except Exception:
    pass

with open(last_path, "w", encoding="utf-8") as f:
    json.dump(rec, f, ensure_ascii=False, indent=2)
' "$RADAR_HISTORY_FILE" "$RADAR_FRAMES_DIR" "$RADAR_LAST_FILE" "$tile_png" "$MAX_RADAR_HISTORY" <<<"$meta_json" || true
}

radar_png_path() {
  # Resolve a radar record PNG path (relative to RADAR_DIR or absolute).
  python3 -c '
import json,sys,os
rec=json.loads(sys.argv[1])
base=sys.argv[2]
rel=rec.get("png") or ""
if not rel:
    sys.exit(1)
print(rel if os.path.isabs(rel) else os.path.join(base, rel))
' "$1" "$RADAR_DIR"
}

print_radar_history_list() {
  if [[ ! -s "$RADAR_HISTORY_FILE" ]]; then
    echo "No saved radar searches yet. Run a radar lookup first."
    return 0
  fi
  python3 -c '
import json,sys,os
path=sys.argv[1]
base=os.path.dirname(path)
rows=[]
with open(path, encoding="utf-8") as f:
    for ln in f:
        ln=ln.strip()
        if not ln:
            continue
        try:
            rows.append(json.loads(ln))
        except Exception:
            pass
rows.reverse()
print("#   %-22s  %-32s  %-20s %s" % ("Saved","Location","Radar frame","Tile"))
print("-"*86)
for num, r in enumerate(rows, 1):
    ts=(r.get("fetched_at") or "")[:19].replace("T"," ")
    lab=(r.get("label") or r.get("query") or "?")[:32]
    frame=(r.get("radar_time") or "")[:20]
    tile="z%s (%s,%s)" % (r.get("zoom","?"), r.get("tx","?"), r.get("ty","?"))
    rel=r.get("png") or ""
    png=rel if os.path.isabs(rel) else os.path.join(base, rel)
    mark="" if (rel and os.path.isfile(png)) else " (missing image)"
    print("%-3d %-22s  %-32s  %-20s %s%s" % (num, ts, lab, frame, tile, mark))
print()
print("Tip: weath --radar-history N   replay saved radar N offline (1 = most recent)")
print("     Last %s searches are kept." % sys.argv[2])
' "$RADAR_HISTORY_FILE" "$MAX_RADAR_HISTORY"
}

show_radar_history_entry() {
  local n=$1
  python3 -c '
import json,sys
path=sys.argv[1]
n=int(sys.argv[2])
rows=[]
with open(path, encoding="utf-8") as f:
    for ln in f:
        ln=ln.strip()
        if ln:
            try: rows.append(json.loads(ln))
            except: pass
if not rows:
    print("No saved radar searches.", file=sys.stderr); sys.exit(1)
idx=len(rows)-n
if idx<0 or idx>=len(rows):
    print("No radar history entry #%s. Have %s entries." % (n, len(rows)), file=sys.stderr)
    sys.exit(1)
print(json.dumps(rows[idx]))
' "$RADAR_HISTORY_FILE" "$n"
}

# Newest saved radar, optionally matching a lat/lon tile.
# $4 = 1 to require the same zoom (used when zooming).
find_saved_radar() {
  local lat=${1:-} lon=${2:-} zoom=${3:-${WEATH_RADAR_ZOOM:-7}} strict=${4:-0}
  python3 -c '
import json,sys,os,math
path=sys.argv[1]
lat=sys.argv[2]
lon=sys.argv[3]
zoom=int(sys.argv[4])
rows=[]
if os.path.isfile(path):
    with open(path, encoding="utf-8") as f:
        for ln in f:
            ln=ln.strip()
            if not ln:
                continue
            try: rows.append(json.loads(ln))
            except: pass
if not rows:
    sys.exit(1)

def tile(la, lo, z):
    n=2**z
    x=int((float(lo)+180.0)/360.0*n)
    lat_r=math.radians(float(la))
    y=int((1.0-math.asinh(math.tan(lat_r))/math.pi)/2.0*n)
    return max(0,min(n-1,x)), max(0,min(n-1,y))

pick=rows[-1]
strict=sys.argv[5] if len(sys.argv)>5 else "0"
matched=None
if lat and lon:
    try:
        tx,ty=tile(lat, lon, zoom)
        for r in reversed(rows):
            if int(r.get("zoom") or zoom)==zoom and int(r.get("tx") or -1)==tx and int(r.get("ty") or -1)==ty:
                matched=r
                break
    except Exception:
        pass
if matched is not None:
    pick=matched
elif strict=="1":
    sys.exit(1)
print(json.dumps(pick))
' "$RADAR_HISTORY_FILE" "$lat" "$lon" "$zoom" "$strict"
}

# Replay a saved radar record with no network.
replay_radar() {
  local rec_json=$1
  local note=${2:-"(saved - offline)"}
  local lat lon label zoom tx ty when png cols rows
  lat=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("lat",""))' <<<"$rec_json")
  lon=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("lon",""))' <<<"$rec_json")
  label=$(python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("label") or d.get("query") or "")' <<<"$rec_json")
  zoom=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("zoom",7))' <<<"$rec_json")
  tx=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("tx",""))' <<<"$rec_json")
  ty=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("ty",""))' <<<"$rec_json")
  when=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("radar_time") or "")' <<<"$rec_json")
  png=$(radar_png_path "$rec_json") || {
    echo "Error: radar record has no image path." >&2
    return 1
  }
  read -r cols rows < <(radar_grid_size)
  local bbox
  bbox=$(bbox_csv_from_json <<<"$rec_json" || true)
  if [[ -z "$bbox" && -n "$lat" && -n "$lon" ]]; then
    bbox=$(approx_bbox_csv "$lat" "$lon" || true)
  fi

  local view
  view=$(python3 -c '
import json,sys
d=json.load(sys.stdin)
v=d.get("view") or {}
if all(k in v for k in ("south","north","west","east")):
    print("%.6f,%.6f,%.6f,%.6f" % (float(v["south"]), float(v["north"]), float(v["west"]), float(v["east"])))
' <<<"$rec_json" 2>/dev/null || true)

  echo "${C_BOLD}${C_CYAN}  Radar${C_RESET}  ${C_DIM}${label}  (${lat}, ${lon})${C_RESET}"
  echo "${C_DIM}  ${note}${C_RESET}"
  hr
  render_radar_png "$png" "$cols" "$rows" "$lat" "$lon" "$zoom" "$tx" "$ty" "$bbox" "$view" || return 1
  set_last_radar "$png" "$label" "$when" "$lat" "$lon" "$zoom" "$tx" "$ty" "$bbox" "$view"
  print_radar_legend "$zoom" "$tx" "$ty" "$when" "offline archive - no live fetch" "$lat" "$lon" "$bbox" "$view"
}

show_radar() {
  local lat=$1 lon=$2 label=${3:-} bbox=${4:-}
  local zoom
  zoom=$(radar_clamp_zoom "${5:-${WEATH_RADAR_ZOOM:-7}}")
  local cols rows
  read -r cols rows < <(radar_grid_size)
  if [[ -z "$bbox" && -n "$lat" && -n "$lon" ]]; then
    bbox=$(approx_bbox_csv "$lat" "$lon" || true)
  fi

  if ! radar_convert_bin >/dev/null; then
    echo "Error: ImageMagick (convert or magick) required for radar." >&2
    return 1
  fi

  echo "${C_BOLD}${C_CYAN}  Radar${C_RESET}  ${C_DIM}${label}  (${lat}, ${lon})${C_RESET}"
  hr
  echo "${C_DIM}  Fetching centered map + radar (z=${zoom})...${C_RESET}"

  local meta host path time_epoch
  meta=$(http_get "https://api.rainviewer.com/public/weather-maps.json") || {
    echo "Error: could not reach RainViewer." >&2
    local saved
    if saved=$(find_saved_radar "$lat" "$lon" "$zoom"); then
      echo "${C_DIM}  Restoring last saved radar for this area (offline).${C_RESET}"
      replay_radar "$saved" "(restored - offline)"
      return
    fi
    echo "No saved radar to restore. Run a radar lookup while online first." >&2
    return 1
  }
  read -r host path time_epoch < <(python3 -c '
import json,sys
d=json.load(sys.stdin)
host=d["host"]
past=d.get("radar",{}).get("past") or []
if not past:
    print("", "", "0"); raise SystemExit(1)
last=past[-1]
print(host, last["path"], last["time"])
' <<<"$meta")

  local tile_png tx ty south north west east view
  tile_png="$CACHE_DIR/radar_view_z${zoom}_$(python3 -c 'import sys; print("%.4f_%.4f"%(float(sys.argv[1]),float(sys.argv[2])))' "$lat" "$lon").png"
  if ! read -r tx ty south north west east < <(compose_centered_radar "$lat" "$lon" "$zoom" "$host" "$path" "$tile_png"); then
    echo "Error: failed to build centered radar view." >&2
    local saved
    if saved=$(find_saved_radar "$lat" "$lon" "$zoom" 1); then
      echo "${C_DIM}  Restoring last saved radar for this area (offline).${C_RESET}"
      replay_radar "$saved" "(restored - offline)"
      return
    fi
    return 1
  fi
  view="${south},${north},${west},${east}"
  draw_admin1_on_png "$tile_png" "$south" "$north" "$west" "$east"

  local when
  when=$(python3 -c 'import datetime,sys; print(datetime.datetime.utcfromtimestamp(int(sys.argv[1])).strftime("%Y-%m-%d %H:%M UTC"))' "$time_epoch" 2>/dev/null || echo "$time_epoch")

  local snap
  snap=$(python3 -c '
import json,sys,datetime
bbox=sys.argv[11]
view=sys.argv[12]
bb=None
if bbox:
    parts=bbox.split(",")
    if len(parts)==4:
        try:
            s,n,w,e=map(float, parts)
            bb={"south":s,"north":n,"west":w,"east":e}
        except Exception:
            bb=None
vw=None
if view:
    parts=view.split(",")
    if len(parts)==4:
        try:
            s,n,w,e=map(float, parts)
            vw={"south":s,"north":n,"west":w,"east":e}
        except Exception:
            vw=None
print(json.dumps({
  "lat": float(sys.argv[1]),
  "lon": float(sys.argv[2]),
  "label": sys.argv[3],
  "zoom": int(sys.argv[4]),
  "tx": int(sys.argv[5]),
  "ty": int(sys.argv[6]),
  "cols": int(sys.argv[7]),
  "rows": int(sys.argv[8]),
  "time_epoch": int(sys.argv[9]) if str(sys.argv[9]).isdigit() else sys.argv[9],
  "radar_time": sys.argv[10],
  "bbox": bb,
  "view": vw,
  "fetched_at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
}))
' "$lat" "$lon" "$label" "$zoom" "$tx" "$ty" "$cols" "$rows" "$time_epoch" "$when" "$bbox" "$view")
  save_radar_snapshot "$tile_png" "$snap"

  render_radar_png "$tile_png" "$cols" "$rows" "$lat" "$lon" "$zoom" "$tx" "$ty" "$bbox" "$view" || return 1
  local archived=""
  if [[ -f "$RADAR_LAST_FILE" ]]; then
    archived=$(python3 -c '
import json,sys,os
p=sys.argv[1]; base=sys.argv[2]
try:
    rec=json.load(open(p,encoding="utf-8"))
except Exception:
    sys.exit(0)
rel=rec.get("png") or ""
if not rel:
    sys.exit(0)
print(rel if os.path.isabs(rel) else os.path.join(base, rel))
' "$RADAR_LAST_FILE" "$RADAR_DIR" 2>/dev/null || true)
  fi
  if [[ -n "$archived" && -f "$archived" ]]; then
    set_last_radar "$archived" "$label" "$when" "$lat" "$lon" "$zoom" "$tx" "$ty" "$bbox" "$view"
  else
    set_last_radar "$tile_png" "$label" "$when" "$lat" "$lon" "$zoom" "$tx" "$ty" "$bbox" "$view"
  fi
  print_radar_legend "$zoom" "$tx" "$ty" "$when" "" "$lat" "$lon" "$bbox" "$view"
}

radar_for_weather() {
  local weather_json=$1
  local lat lon label bbox z geo
  lat=$(python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("lat") or d.get("geo",{}).get("lat"))' <<<"$weather_json")
  lon=$(python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("lon") or d.get("geo",{}).get("lon"))' <<<"$weather_json")
  label=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("label",""))' <<<"$weather_json")
  bbox=$(bbox_csv_from_json <<<"$weather_json" || true)
  geo=$(python3 -c 'import json,sys; d=json.load(sys.stdin); print(json.dumps(d.get("geo") or d))' <<<"$weather_json")
  z=$(radar_zoom_for_geo <<<"$geo")
  show_radar "$lat" "$lon" "$label" "$bbox" "$z"
}

# ---------------------------------------------------------------------------
# Lookup pipeline
# ---------------------------------------------------------------------------
lookup() {
  local q=$1
  local with_radar=${2:-0}
  echo "${C_DIM}Resolving ${q}...${C_RESET}"
  local geo weather
  geo=$(geocode_location "$q") || return 1
  local glabel
  glabel=$(python3 -c 'import json,sys; print(json.load(sys.stdin)["label"])' <<<"$geo")
  echo "${C_DIM}Location: ${glabel}${C_RESET}"
  echo "${C_DIM}Fetching weather...${C_RESET}"
  weather=$(fetch_weather "$geo") || return 1
  save_history "$weather"
  print_weather "$weather"
  if [[ "$with_radar" == "1" ]]; then
    radar_for_weather "$weather"
  fi
}

# ---------------------------------------------------------------------------
# RSS feeds
# ---------------------------------------------------------------------------
http_get_rss() {
  local url=$1
  curl -fsSL --max-time 25 -A "$USER_AGENT" \
    -H "Accept: application/rss+xml, application/atom+xml, application/xml, text/xml;q=0.9, */*;q=0.8" \
    "$url"
}

rss_feed_count() {
  python3 -c '
import json,sys,os
p=sys.argv[1]
if not os.path.isfile(p):
    print(0); raise SystemExit
try:
    d=json.load(open(p,encoding="utf-8"))
except Exception:
    print(0); raise SystemExit
print(len(d) if isinstance(d,list) else 0)
' "$RSS_FEEDS_FILE"
}

print_rss_feed_list() {
  python3 -c '
import json,sys,os
p=sys.argv[1]
if not os.path.isfile(p):
    print("No RSS feeds saved.")
    raise SystemExit
try:
    feeds=json.load(open(p,encoding="utf-8"))
except Exception:
    print("No RSS feeds saved.")
    raise SystemExit
if not isinstance(feeds,list) or not feeds:
    print("No RSS feeds saved. Use menu 9 then Add feed.")
    raise SystemExit
print("#   %-28s  %s" % ("Title","URL"))
print("-"*78)
for i,f in enumerate(feeds,1):
    title=(f.get("title") or "Untitled")[:28]
    url=(f.get("url") or "")[:46]
    print("%-3d %-28s  %s" % (i, title, url))
print()
print("%d feed(s)." % len(feeds))
' "$RSS_FEEDS_FILE"
}

rss_add_feed() {
  local url=${1:-}
  if [[ -z "$url" ]]; then
    read -r -p "Feed URL: " url || return 1
  fi
  url=$(echo "$url" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
  if [[ ! "$url" =~ ^https?:// ]]; then
    echo "Error: URL must start with http:// or https://"
    return 1
  fi
  echo "${C_DIM}Fetching feed...${C_RESET}"
  local xml
  if ! xml=$(http_get_rss "$url" 2>/dev/null); then
    echo "Error: could not download feed."
    return 1
  fi
  local title
  title=$(python3 -c '
import json,sys,os,datetime,html,re
from xml.etree import ElementTree as ET
from urllib.parse import urlparse

path, url = sys.argv[1], sys.argv[2]
raw = sys.stdin.read()
if raw.startswith("\ufeff"):
    raw = raw[1:]

def lname(tag):
    return tag.split("}",1)[-1].lower() if "}" in tag else tag.lower()

def text_of(el):
    if el is None:
        return ""
    return html.unescape(re.sub(r"\s+"," ", "".join(el.itertext()))).strip()

title = ""
try:
    root = ET.fromstring(raw)
except Exception as e:
    print("Error: not a valid RSS/Atom document.", file=sys.stderr)
    sys.exit(1)

# RSS channel/title or Atom feed/title
if lname(root.tag) == "rss":
    ch = None
    for c in root:
        if lname(c.tag) == "channel":
            ch = c
            break
    if ch is not None:
        for c in ch:
            if lname(c.tag) == "title":
                title = text_of(c)
                break
elif lname(root.tag) == "feed":
    for c in root:
        if lname(c.tag) == "title":
            title = text_of(c)
            break
elif lname(root.tag) == "rdf":
    for c in root:
        if lname(c.tag) == "channel":
            for cc in c:
                if lname(cc.tag) == "title":
                    title = text_of(cc)
                    break

if not title:
    title = urlparse(url).netloc or url
title = title[:80]

feeds = []
if os.path.isfile(path):
    try:
        feeds = json.load(open(path, encoding="utf-8"))
        if not isinstance(feeds, list):
            feeds = []
    except Exception:
        feeds = []

for f in feeds:
    if (f.get("url") or "").rstrip("/") == url.rstrip("/"):
        print("That feed is already saved: %s" % (f.get("title") or url), file=sys.stderr)
        sys.exit(2)

nid = 1
for f in feeds:
    try:
        nid = max(nid, int(f.get("id") or 0) + 1)
    except Exception:
        pass

feeds.append({
    "id": nid,
    "url": url,
    "title": title,
    "added_at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
})
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
with open(path, "w", encoding="utf-8") as fh:
    json.dump(feeds, fh, ensure_ascii=False, indent=2)
    fh.write("\n")
print(title)
' "$RSS_FEEDS_FILE" "$url" <<<"$xml") || return 1
  echo "Added: $title"
}

rss_remove_feed() {
  print_rss_feed_list
  local n
  local count
  count=$(rss_feed_count)
  if [[ "$count" -eq 0 ]]; then
    return 0
  fi
  if [[ -n "${1:-}" && "$1" =~ ^[0-9]+$ ]]; then
    n=$1
  else
    read -r -p "Feed # to remove (Enter to cancel): " n || return 1
  fi
  [[ "$n" =~ ^[0-9]+$ ]] || return 0
  python3 -c '
import json,sys,os
path=sys.argv[1]
n=int(sys.argv[2])
feeds=json.load(open(path,encoding="utf-8"))
if not isinstance(feeds,list) or n<1 or n>len(feeds):
    print("No feed #%s." % n, file=sys.stderr)
    sys.exit(1)
removed=feeds.pop(n-1)
with open(path,"w",encoding="utf-8") as fh:
    json.dump(feeds, fh, ensure_ascii=False, indent=2)
    fh.write("\n")
print("Removed: %s" % (removed.get("title") or removed.get("url") or n))
' "$RSS_FEEDS_FILE" "$n"
}

rss_collect_headlines() {
  local feeds xml tmp status
  tmp=$(mktemp)
  python3 -c '
import json,sys,os
p=sys.argv[1]
feeds=[]
if os.path.isfile(p):
    try:
        feeds=json.load(open(p,encoding="utf-8"))
    except Exception:
        feeds=[]
if not isinstance(feeds,list) or not feeds:
    sys.exit(3)
json.dump(feeds, sys.stdout)
' "$RSS_FEEDS_FILE" > "$tmp" || {
    rm -f "$tmp"
    echo "No RSS feeds saved. Add a feed first." >&2
    return 1
  }

  echo "${C_DIM}Fetching headlines...${C_RESET}" >&2
  local out
  out=$(mktemp)
  printf '%s\n' '{"ok":0,"feeds":0,"errors":[],"items":[]}' > "$out"

  python3 -c '
import json,sys,os,html,re,subprocess
from xml.etree import ElementTree as ET
from email.utils import parsedate_to_datetime
from datetime import datetime, timezone

feeds_path, out_path, ua, per_feed, max_items = sys.argv[1:6]
per_feed=int(per_feed); max_items=int(max_items)
feeds=json.load(open(feeds_path,encoding="utf-8"))

def lname(tag):
    return tag.split("}",1)[-1].lower() if "}" in tag else tag.lower()

def text_of(el):
    if el is None:
        return ""
    return html.unescape(re.sub(r"\s+"," ", "".join(el.itertext()))).strip()

def child(el, *names):
    want=set(n.lower() for n in names)
    for c in list(el):
        if lname(c.tag) in want:
            return c
    return None

def link_of(el):
    # RSS: <link>url</link>   Atom: <link href="url"/>
    for c in list(el):
        if lname(c.tag) != "link":
            continue
        href=(c.attrib.get("href") or c.attrib.get("HREF") or "").strip()
        rel=(c.attrib.get("rel") or "alternate").lower()
        if href and rel in ("alternate","self",""):
            return href
        t=text_of(c)
        if t.startswith("http"):
            return t
    # guid sometimes is a permalink
    g=child(el,"guid","id")
    if g is not None:
        t=text_of(g)
        if t.startswith("http"):
            return t
    return ""

def parse_when(s):
    if not s:
        return None, ""
    s=s.strip()
    try:
        dt=parsedate_to_datetime(s)
        if dt.tzinfo is None:
            dt=dt.replace(tzinfo=timezone.utc)
        return dt, dt.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M")
    except Exception:
        pass
    for fmt in ("%Y-%m-%dT%H:%M:%SZ","%Y-%m-%dT%H:%M:%S%z","%Y-%m-%d %H:%M:%S","%Y-%m-%d"):
        try:
            dt=datetime.strptime(s.replace("Z","+0000") if fmt.endswith("%z") and s.endswith("Z") else s, fmt)
            if dt.tzinfo is None:
                dt=dt.replace(tzinfo=timezone.utc)
            return dt, dt.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M")
        except Exception:
            continue
    return None, s[:16]

def items_from_xml(raw, feed_title):
    if raw.startswith("\ufeff"):
        raw=raw[1:]
    try:
        root=ET.fromstring(raw)
    except Exception:
        return []
    items=[]
    tag=lname(root.tag)
    nodes=[]
    if tag=="rss":
        for ch in root:
            if lname(ch.tag)=="channel":
                for it in ch:
                    if lname(it.tag)=="item":
                        nodes.append(it)
    elif tag=="feed":
        for it in root:
            if lname(it.tag)=="entry":
                nodes.append(it)
    elif tag=="rdf":
        for it in root:
            if lname(it.tag)=="item":
                nodes.append(it)
    else:
        for it in root.iter():
            if lname(it.tag) in ("item","entry"):
                nodes.append(it)

    for it in nodes:
        title=text_of(child(it,"title")) or "(no title)"
        link=link_of(it)
        date_el=child(it,"pubdate","published","updated","date","dc:date")
        # dc:date localname is date
        if date_el is None:
            for c in list(it):
                if lname(c.tag) in ("pubdate","published","updated","date"):
                    date_el=c
                    break
        dt, when = parse_when(text_of(date_el) if date_el is not None else "")
        body=text_of(child(it,"description","summary","content","content:encoded"))
        if not body:
            for c in list(it):
                if lname(c.tag) in ("description","summary","content","encoded"):
                    body=text_of(c)
                    break
        items.append({
            "title": title[:200],
            "link": link,
            "when": when,
            "ts": dt.timestamp() if dt else 0,
            "feed": feed_title[:24],
            "summary": body[:4000],
        })
    return items

ok=0
all_items=[]
errors=[]
for f in feeds:
    url=f.get("url") or ""
    ftitle=f.get("title") or url
    if not url:
        continue
    try:
        raw=subprocess.check_output(
            ["curl","-fsSL","--max-time","25","-A",ua,
             "-H","Accept: application/rss+xml, application/atom+xml, application/xml, text/xml;q=0.9, */*;q=0.8",
             url],
            stderr=subprocess.DEVNULL)
        raw=raw.decode("utf-8","replace")
    except Exception:
        errors.append(ftitle)
        continue
    got=items_from_xml(raw, ftitle)[:per_feed]
    if got:
        ok += 1
        all_items.extend(got)
    else:
        errors.append(ftitle)

all_items.sort(key=lambda r: r.get("ts") or 0, reverse=True)
all_items=all_items[:max_items]
for r in all_items:
    r.pop("ts", None)
json.dump({"ok":ok,"feeds":len(feeds),"errors":errors,"items":all_items}, open(out_path,"w",encoding="utf-8"))
' "$tmp" "$out" "$USER_AGENT" "$MAX_RSS_PER_FEED" "$MAX_RSS_ITEMS" || true
  rm -f "$tmp"
  printf '%s\n' "$out"
}

rss_draw_headlines() {
  local pack=$1 selected=$2
  python3 -c '
import json,sys,os,shutil
path=sys.argv[1]
sel=int(sys.argv[2])
pack=json.load(open(path,encoding="utf-8"))
items=pack.get("items") or []
cols=shutil.get_terminal_size((80,24)).columns
rows=shutil.get_terminal_size((80,24)).lines
ok=pack.get("ok",0); nf=pack.get("feeds",0)
errs=pack.get("errors") or []
# header + footer + status
view=max(6, rows-7)
n=len(items)
if n==0:
    print("RSS headlines")
    print("-"*min(78, cols))
    print("No headlines.")
    if errs:
        print("Failed: %s" % ", ".join(errs)[:cols])
    raise SystemExit
sel=max(0, min(n-1, sel))
top=0
if sel>=view:
    top=sel-view+1
# keep a window
if top>sel:
    top=sel
if top<0:
    top=0

print("RSS headlines  %d item(s)  feeds ok %d/%d" % (n, ok, nf))
print("Up/Down move   Enter read   o browser   q back")
print("-"*min(78, cols))
feed_w=12
when_w=16
# " > " + feed + "  " + when + "  " + title
title_w=max(16, cols-feed_w-when_w-8)
for i in range(top, min(n, top+view)):
    it=items[i]
    mark=">" if i==sel else " "
    feed=(it.get("feed") or "?")[:feed_w].ljust(feed_w)
    when=(it.get("when") or "")[:when_w].ljust(when_w)
    title=(it.get("title") or "")[:title_w]
    line="%s %s  %s  %s" % (mark, feed, when, title)
    if i==sel:
        print("\033[7m"+line[:cols]+"\033[0m")
    else:
        print(line[:cols])
print("-"*min(78, cols))
cur=items[sel]
link=cur.get("link") or "(no link)"
print((link)[:cols])
if errs:
    print("Failed feeds: %s" % ", ".join(errs)[: max(0, cols-14)])
' "$pack" "$selected"
}

rss_fetch_article_text() {
  local url=$1
  python3 -c '
import sys,re,html,urllib.request
from html.parser import HTMLParser

url=sys.argv[1]
ua=sys.argv[2]

class Extract(HTMLParser):
    def __init__(self):
        super().__init__()
        self.skip=0
        self.parts=[]
        self._in=["html"]
    def handle_starttag(self, tag, attrs):
        tag=tag.lower()
        self._in.append(tag)
        if tag in ("script","style","nav","footer","noscript","svg"):
            self.skip += 1
        if tag in ("p","br","div","h1","h2","h3","li","tr"):
            self.parts.append("\n")
    def handle_endtag(self, tag):
        tag=tag.lower()
        if tag in ("script","style","nav","footer","noscript","svg") and self.skip:
            self.skip -= 1
        if self._in:
            self._in.pop()
        if tag in ("p","div","h1","h2","h3","li"):
            self.parts.append("\n")
    def handle_data(self, data):
        if self.skip:
            return
        t=html.unescape(data)
        if t.strip():
            self.parts.append(t)

req=urllib.request.Request(url, headers={"User-Agent":ua,"Accept":"text/html,application/xhtml+xml;q=0.9,*/*;q=0.8"})
try:
    with urllib.request.urlopen(req, timeout=20) as r:
        raw=r.read()
        cs=(r.headers.get_content_charset() or "utf-8")
        text=raw.decode(cs, "replace")
except Exception as e:
    print("Could not fetch article: %s" % e)
    sys.exit(0)
# drop obvious junk
text=re.sub(r"(?is)<(script|style|noscript).*?>.*?</\\1>", " ", text)
p=Extract()
try:
    p.feed(text)
except Exception:
    pass
out=re.sub(r"[ \t]+", " ", "".join(p.parts))
out=re.sub(r"\n[ \t]+", "\n", out)
out=re.sub(r"\n{3,}", "\n\n", out).strip()
if not out:
    print("(No readable text on that page.)")
else:
    print(out[:12000])
' "$url" "$USER_AGENT"
}

rss_show_article() {
  local pack=$1 idx=$2
  local title link when feed summary
  title=$(python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); i=int(sys.argv[2]); it=(d.get("items") or [None])[i] if i>=0 else None; print((it or {}).get("title") or "")' "$pack" "$idx")
  link=$(python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); i=int(sys.argv[2]); it=(d.get("items") or [None])[i] if i>=0 else None; print((it or {}).get("link") or "")' "$pack" "$idx")
  when=$(python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); i=int(sys.argv[2]); it=(d.get("items") or [None])[i] if i>=0 else None; print((it or {}).get("when") or "")' "$pack" "$idx")
  feed=$(python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); i=int(sys.argv[2]); it=(d.get("items") or [None])[i] if i>=0 else None; print((it or {}).get("feed") or "")' "$pack" "$idx")
  summary=$(python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); i=int(sys.argv[2]); it=(d.get("items") or [None])[i] if i>=0 else None; print((it or {}).get("summary") or "")' "$pack" "$idx")

  tput cnorm 2>/dev/null || true
  printf '\033[2J\033[H'
  echo "${C_BOLD}${title}${C_RESET}"
  echo "${C_DIM}${feed}  ${when}${C_RESET}"
  [[ -n "$link" ]] && echo "${C_DIM}${link}${C_RESET}"
  hr
  if [[ -n "$summary" ]]; then
    echo "$summary" | python3 -c '
import sys,re,html,textwrap
t=sys.stdin.read()
t=re.sub(r"<[^>]+>"," ",t)
t=html.unescape(t)
t=re.sub(r"\s+"," ",t).strip()
print("\n".join(textwrap.wrap(t, 78)[:40]))
'
    echo
  fi
  if [[ -n "$link" && "$link" != "(no link)" ]]; then
    echo "${C_DIM}Fetching article text...${C_RESET}"
    echo
    rss_fetch_article_text "$link" | python3 -c '
import sys,textwrap
t=sys.stdin.read()
for para in t.split("\n"):
    para=para.strip()
    if not para:
        print()
        continue
    print("\n".join(textwrap.wrap(para, 78)))
'
  fi
  echo
  echo -n "o open in browser   q back: "
  local k
  k=$(rss_read_key)
  echo
  if [[ "$k" == "o" || "$k" == "O" ]]; then
    rss_open_url "$link" || true
    echo -n "Press any key to continue: "
    read -r -n 1 -s _ || true
  fi
}

rss_open_url() {
  local url=$1
  if [[ -z "$url" || "$url" == "(no link)" ]]; then
    echo "No link for this headline."
    return 1
  fi
  if command -v xdg-open >/dev/null 2>&1; then
    xdg-open "$url" >/dev/null 2>&1 &
    return 0
  fi
  if command -v gio >/dev/null 2>&1; then
    gio open "$url" >/dev/null 2>&1 &
    return 0
  fi
  if command -v sensible-browser >/dev/null 2>&1; then
    sensible-browser "$url" >/dev/null 2>&1 &
    return 0
  fi
  if command -v w3m >/dev/null 2>&1; then
    w3m "$url"
    return 0
  fi
  if command -v lynx >/dev/null 2>&1; then
    lynx "$url"
    return 0
  fi
  echo "Open this URL in a browser:"
  echo "  $url"
}

rss_read_key() {
  local k rest
  IFS= read -r -s -n 1 k || { echo EOF; return 0; }
  if [[ "$k" == $'\x1b' ]]; then
    IFS= read -r -s -n 1 -t 0.05 rest || { echo ESC; return 0; }
    if [[ "$rest" == "[" ]]; then
      IFS= read -r -s -n 1 -t 0.05 rest || { echo ESC; return 0; }
      case "$rest" in
        A) echo UP ;;
        B) echo DOWN ;;
        5)
          IFS= read -r -s -n 1 -t 0.05 _ || true
          echo PGUP
          ;;
        6)
          IFS= read -r -s -n 1 -t 0.05 _ || true
          echo PGDN
          ;;
        *) echo ESC ;;
      esac
    else
      echo ESC
    fi
  elif [[ -z "$k" || "$k" == $'\n' || "$k" == $'\r' ]]; then
    echo ENTER
  else
    printf '%s\n' "$k"
  fi
}

rss_browse_headlines() {
  local pack sel n key url
  pack=$(rss_collect_headlines) || return 1
  if [[ ! -f "$pack" ]]; then
    echo "Error: could not collect headlines."
    return 1
  fi
  n=$(python3 -c 'import json,sys; print(len((json.load(open(sys.argv[1])).get("items") or [])))' "$pack")
  if [[ "$n" -eq 0 ]]; then
    rss_draw_headlines "$pack" 0
    rm -f "$pack"
    return 0
  fi

  sel=0
  RSS_BROWSER_PACK=$pack
  RSS_BROWSER_STTY=$(stty -g 2>/dev/null || true)
  tput civis 2>/dev/null || true
  rss_browse_cleanup() {
    tput cnorm 2>/dev/null || true
    [[ -n "${RSS_BROWSER_STTY:-}" ]] && stty "$RSS_BROWSER_STTY" 2>/dev/null || true
    [[ -n "${RSS_BROWSER_PACK:-}" && -f "$RSS_BROWSER_PACK" ]] && rm -f "$RSS_BROWSER_PACK"
    RSS_BROWSER_PACK=""
    trap - RETURN INT
  }
  trap rss_browse_cleanup RETURN INT

  while true; do
    printf '\033[2J\033[H'
    rss_draw_headlines "$pack" "$sel"
    key=$(rss_read_key)
    case "$key" in
      UP|k|K)
        if (( sel > 0 )); then sel=$((sel-1)); fi
        ;;
      DOWN|j|J)
        if (( sel < n-1 )); then sel=$((sel+1)); fi
        ;;
      PGUP)
        sel=$((sel-10))
        if (( sel < 0 )); then sel=0; fi
        ;;
      PGDN)
        sel=$((sel+10))
        if (( sel > n-1 )); then sel=$((n-1)); fi
        ;;
      ENTER|r|R)
        rss_show_article "$pack" "$sel"
        ;;
      o|O)
        url=$(python3 -c 'import json,sys
p=json.load(open(sys.argv[1]))
i=int(sys.argv[2])
items=p.get("items") or []
print(items[i].get("link") or "" if 0<=i<len(items) else "")
' "$pack" "$sel")
        if ! rss_open_url "$url"; then
          echo
          echo -n "Press any key to continue: "
          read -r -n 1 -s _ || true
        fi
        ;;
      q|Q|ESC|EOF|b|B)
        break
        ;;
    esac
  done
}

rss_menu() {
  while true; do
    hr
    echo "${C_BOLD}RSS feeds${C_RESET}"
    echo "  ${C_GREEN}1${C_RESET}) Headlines"
    echo "  ${C_GREEN}2${C_RESET}) Add feed"
    echo "  ${C_GREEN}3${C_RESET}) Remove feed"
    echo "  ${C_GREEN}4${C_RESET}) List feeds"
    echo "  ${C_GREEN}b${C_RESET}) Back"
    echo
    local rc
    rc=$(rss_feed_count)
    echo "${C_DIM}${rc} feed(s) saved.${C_RESET}"
    echo
    local choice
    read -r -p "RSS choice: " choice || return 0
    case "$choice" in
      1)
        rss_browse_headlines || true
        ;;
      2)
        rss_add_feed || true
        ;;
      3)
        rss_remove_feed || true
        ;;
      4)
        print_rss_feed_list
        ;;
      b|B|q|Q|"")
        return 0
        ;;
      *)
        echo "Unknown choice."
        ;;
    esac
  done
}

# ---------------------------------------------------------------------------
# Interactive menu
# ---------------------------------------------------------------------------
menu_set_location() {
  local loc
  read -r -p "Location (zip / city / address): " loc || return 1
  [[ -n "$loc" ]] || return 1
  lookup "$loc" 0
}

menu_weather_forecast() {
  local last loc
  if last=$(load_last 2>/dev/null); then
    loc=$(python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("query") or d.get("label") or "")' <<<"$last")
    if [[ -n "$loc" ]]; then
      lookup "$loc" 0
      return
    fi
  fi
  echo "No location set yet."
  menu_set_location
}

menu_radar_now() {
  local last loc
  if last=$(load_last 2>/dev/null); then
    radar_for_weather "$last"
    after_radar_view
    return
  fi
  echo "No location set yet."
  read -r -p "Location for radar (zip / city / address): " loc || return 1
  if [[ -n "$loc" ]]; then
    lookup "$loc" 1
    after_radar_view
  fi
}

interactive_menu() {
  WEATH_MENU=1
  banner
  local last=""
  if last=$(load_last 2>/dev/null); then
    print_weather "$last" "(last saved query - cached)"
  else
    echo "${C_DIM}No previous query on file. Press L to set a location.${C_RESET}"
    echo
  fi
  echo "${C_DIM}Hotkeys: W weather forecast   R radar   L set location${C_RESET}"
  echo
  local rc
  rc=$(radar_history_count)
  if [[ "$rc" -gt 0 ]]; then
    echo "${C_DIM}Saved radar searches: ${rc} (last ${MAX_RADAR_HISTORY} kept). Menu 7 reviews them offline.${C_RESET}"
    echo
  fi

  while true; do
    hr
    echo "${C_BOLD}Menu${C_RESET}"
    echo "  Hotkeys:  ${C_GREEN}W${C_RESET} weather forecast   ${C_GREEN}R${C_RESET} radar   ${C_GREEN}L${C_RESET} set location"
    echo
    echo "  ${C_GREEN}1${C_RESET}) Look up location (zip / city / address)"
    echo "  ${C_GREEN}2${C_RESET}) Refresh last location"
    echo "  ${C_GREEN}3${C_RESET}) Show radar for last location"
    echo "  ${C_GREEN}4${C_RESET}) Review history"
    echo "  ${C_GREEN}5${C_RESET}) Show last result again"
    echo "  ${C_GREEN}6${C_RESET}) Look up + radar"
    echo "  ${C_GREEN}7${C_RESET}) Review saved radar (offline)"
    echo "  ${C_GREEN}8${C_RESET}) Export last radar to PNG"
    echo "  ${C_GREEN}9${C_RESET}) RSS feeds (headlines, add, remove)"
    echo "  ${C_GREEN}q${C_RESET}) Quit"
    echo
    local choice loc
    echo -n "Choice: "
    IFS= read -r -n 1 choice || exit 0
    echo
    case "$choice" in
      W|w)
        menu_weather_forecast
        ;;
      R|r)
        menu_radar_now
        ;;
      L|l)
        menu_set_location
        ;;
      1)
        menu_set_location
        ;;
      2)
        menu_weather_forecast
        ;;
      3)
        menu_radar_now
        ;;
      4)
        print_history_list
        local hn
        read -r -p "Entry # to view (Enter to skip): " hn || true
        if [[ "$hn" =~ ^[0-9]+$ ]]; then
          local entry
          if entry=$(show_history_entry "$hn"); then
            print_weather "$entry" "(from history #$hn)"
          fi
        fi
        ;;
      5)
        if last=$(load_last 2>/dev/null); then
          print_weather "$last" "(last saved query - cached)"
        else
          echo "No last result."
        fi
        ;;
      6)
        read -r -p "Location: " loc
        if [[ -n "$loc" ]]; then
          lookup "$loc" 1
          after_radar_view
        fi
        ;;
      7)
        print_radar_history_list
        local rn
        read -r -p "Radar # to view offline (Enter to skip): " rn || true
        if [[ "$rn" =~ ^[0-9]+$ ]]; then
          local rentry
          if rentry=$(show_radar_history_entry "$rn"); then
            replay_radar "$rentry" "(saved radar #$rn - offline)"
            after_radar_view
          fi
        fi
        ;;
      8)
        prompt_export_radar || true
        ;;
      9)
        rss_menu
        ;;
      q|Q)
        echo "Goodbye from ${APP_NAME}."
        exit 0
        ;;
      "")
        ;;
      *)
        echo "Unknown key. W weather  R radar  L set location  q quit"
        ;;
    esac
  done
}

usage() {
  cat <<EOF
${APP_NAME} v${VERSION} - ${APP_VENDOR}

Usage:
  weath                     Interactive menu; shows last query on load
                            Hotkeys: W weather forecast  R radar  L set location
  weath <location>          Current weather, forecast, advisories
  weath -r <location>       Same + terminal radar
  weath --radar [location]  Radar only (default: last location)
                            Then + / - zoom, m movie, g GIF, U update, A auto (5 min)
  weath --radar-history     List last 100 saved radar searches
  weath --radar-history <n> Replay saved radar n offline (1 = newest)
  weath --radar-export [n] [file.png]
                            Export saved radar n (default 1) to PNG
  weath --history           List saved queries
  weath --history <n>       Show history entry n (1 = newest)
  weath --last              Print last saved result
  weath --refresh           Re-fetch last location
  weath --rss               Browse RSS headlines (arrow keys, Enter opens)
  weath --rss-add <url>     Add an RSS/Atom feed
  weath --rss-remove [n]    Remove saved feed n (or list)
  weath --rss-list          List saved RSS feeds
  weath -h | --help         This help

Location may be ZIP code, city/state, or street address.

Data stored in: ${DATA_DIR}
  history:       ${HISTORY_FILE}
  last:          ${LAST_FILE}
  radar history: ${RADAR_HISTORY_FILE}
  radar frames:  ${RADAR_FRAMES_DIR}
  state/province: ${ADMIN1_GEOJSON}
  rss feeds:     ${RSS_FEEDS_FILE}

Environment:
  WEATH_DATA_DIR           override data directory
  WEATH_MAX_HISTORY        max history lines (default 100)
  WEATH_MAX_RADAR_HISTORY  max saved radar searches (default 100)
  WEATH_RADAR_COLS         radar width  (default: fit terminal)
  WEATH_RADAR_ROWS         radar height (default: fit terminal)
  WEATH_RADAR_ZOOM         map zoom 4-11 (default 7)
  WEATH_RADAR_ZOOM_MIN     min + / - zoom (default 4)
  WEATH_RADAR_ZOOM_MAX     max + / - zoom (default 11)
  WEATH_DETAIL=1           show detailed forecast text
  WEATH_RSS_PER_FEED       headlines kept per feed (default 25)
  WEATH_MAX_RSS            max headlines shown (default 80)

Radar uses RainViewer tiles rendered with ASCII character 254 (${RADAR_CHAR}),
colored white -> yellow -> red by precipitation intensity.

Requires: curl, python3; ImageMagick (convert/magick) for radar.
Missing tools are detected at startup and you can install them.
EOF
}

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
main() {
  ensure_dependencies
  need_cmd curl
  need_cmd python3
  init_storage

  if [[ $# -eq 0 ]]; then
    interactive_menu
    return
  fi

  case "${1:-}" in
    -h|--help|help)
      usage
      ;;
    --version|-V)
      echo "${APP_NAME} ${VERSION} - ${APP_VENDOR}"
      ;;
    --last)
      if last=$(load_last 2>/dev/null); then
        banner
        print_weather "$last" "(last saved query - cached)"
      else
        echo "No last query saved."
        exit 1
      fi
      ;;
    --history|-H)
      if [[ "${2:-}" =~ ^[0-9]+$ ]]; then
        banner
        entry=$(show_history_entry "$2") || exit 1
        print_weather "$entry" "(from history #$2)"
      else
        banner
        print_history_list
      fi
      ;;
    --refresh)
      last=$(load_last 2>/dev/null) || { echo "No last location."; exit 1; }
      loc=$(python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("query") or d.get("label") or "")' <<<"$last")
      banner
      lookup "$loc" 0
      ;;
    --rss)
      banner
      rss_browse_headlines
      ;;
    --rss-add)
      shift
      [[ $# -ge 1 ]] || { echo "Usage: weath --rss-add <url>"; exit 1; }
      rss_add_feed "$*"
      ;;
    --rss-remove|--rss-rm)
      if [[ "${2:-}" =~ ^[0-9]+$ ]]; then
        rss_remove_feed "$2"
      else
        banner
        rss_remove_feed
      fi
      ;;
    --rss-list)
      banner
      print_rss_feed_list
      ;;
    --radar)
      shift
      banner
      if [[ $# -ge 1 ]]; then
        geo=$(geocode_location "$*") || exit 1
        lat=$(python3 -c 'import json,sys; print(json.load(sys.stdin)["lat"])' <<<"$geo")
        lon=$(python3 -c 'import json,sys; print(json.load(sys.stdin)["lon"])' <<<"$geo")
        label=$(python3 -c 'import json,sys; print(json.load(sys.stdin)["label"])' <<<"$geo")
        bbox=$(bbox_csv_from_json <<<"$geo" || true)
        show_radar "$lat" "$lon" "$label" "$bbox" "$(radar_zoom_for_geo <<<"$geo")"
        after_radar_view
      else
        last=$(load_last 2>/dev/null) || { echo "No last location. Usage: weath --radar <location>"; exit 1; }
        radar_for_weather "$last"
        after_radar_view
      fi
      ;;
    --radar-history|--radar-hist)
      if [[ "${2:-}" =~ ^[0-9]+$ ]]; then
        banner
        rentry=$(show_radar_history_entry "$2") || exit 1
        replay_radar "$rentry" "(saved radar #$2 - offline)"
        after_radar_view
      else
        banner
        print_radar_history_list
      fi
      ;;
    --radar-export|--export-radar)
      shift
      local en dest
      if [[ "${1:-}" =~ ^[0-9]+$ ]]; then
        en=$1
        dest=${2:-}
      else
        en=1
        dest=${1:-}
      fi
      rentry=$(show_radar_history_entry "$en") || exit 1
      png=$(radar_png_path "$rentry") || {
        echo "Error: radar record has no image path." >&2
        exit 1
      }
      LAST_RADAR_LABEL=$(python3 -c 'import json,sys; d=json.load(sys.stdin); print(d.get("label") or d.get("query") or "Radar")' <<<"$rentry")
      LAST_RADAR_WHEN=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("radar_time") or "")' <<<"$rentry")
      LAST_RADAR_LAT=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("lat",""))' <<<"$rentry")
      LAST_RADAR_LON=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("lon",""))' <<<"$rentry")
      LAST_RADAR_ZOOM=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("zoom",""))' <<<"$rentry")
      LAST_RADAR_TX=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("tx",""))' <<<"$rentry")
      LAST_RADAR_TY=$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("ty",""))' <<<"$rentry")
      LAST_RADAR_BBOX=$(bbox_csv_from_json <<<"$rentry" || true)
      LAST_RADAR_VIEW=$(python3 -c '
import json,sys
d=json.load(sys.stdin)
v=d.get("view") or {}
if all(k in v for k in ("south","north","west","east")):
    print("%.6f,%.6f,%.6f,%.6f" % (float(v["south"]), float(v["north"]), float(v["west"]), float(v["east"])))
' <<<"$rentry" 2>/dev/null || true)
      LAST_RADAR_PNG=$png
      dest=${dest:-$(default_radar_export_path)}
      export_radar_view_png "$png" "$dest" || exit 1
      if [[ ! "$dest" =~ \.[Pp][Nn][Gg]$ ]]; then
        dest="${dest}.png"
      fi
      echo "Saved: $dest"
      ;;
    -r|--with-radar)
      shift
      [[ $# -ge 1 ]] || { echo "Usage: weath -r <location>"; exit 1; }
      banner
      lookup "$*" 1
      after_radar_view
      ;;
    -*)
      echo "Unknown option: $1" >&2
      usage >&2
      exit 2
      ;;
    *)
      banner
      lookup "$*" 0
      ;;
  esac
}

main "$@"
