#!/bin/bash

# omarchy:summary=Show or set the location used for weather reports
#
# State lives in ~/.local/state/omarchy/settings/weather.json as
# {"name": ..., "latitude": ..., "longitude": ..., "country": ...}. A missing
# file means the location is auto-detected by geo.omarchy.org, which answers in
# this shape. Coordinates make the weather panel exact; a hand-written
# {"name": "Malibu"} alone works too. A two-letter ISO 3166-1 country code is
# what the panel picks metric or imperial units from, so a pinned place keeps
# its own units when wttr.in cannot be reached.
#
#   (no args)           the current location: the stored name, or the
#                       IP-detected city when nothing is set
#   --set <name> [lat,lon] [--country <code>]
#                       store a location
#   --clear             return to IP auto-detect

LOC_FILE="$HOME/.local/state/omarchy/settings/weather.json"
COORDS_PATTERN='^(-?[0-9]+(\.[0-9]+)?),(-?[0-9]+(\.[0-9]+)?)$'
COUNTRY_PATTERN='^[A-Z]{2}$'
USAGE="Usage: omarchy-weather-location [--set <name> [lat,lon] [--country <code>]|--clear]"

case "${1:-}" in
"")
  name=""
  [[ -f $LOC_FILE ]] && name=$(jq -r '.name // "" | if type == "string" then . else "" end' "$LOC_FILE" 2>/dev/null)
  if [[ -z $name ]]; then
    name=$(curl -fsS --max-time 4 https://geo.omarchy.org/ 2>/dev/null | jq -r '.name // empty' 2>/dev/null)
  fi
  [[ -n $name ]] && echo "$name"
  ;;
--set)
  [[ -n ${2:-} && ${2} != --* ]] || { echo "$USAGE" >&2; exit 1; }
  name=$2
  shift 2
  coords=""
  country=""
  while (( $# > 0 )); do
    case "$1" in
      --country)
        [[ -n ${2:-} ]] || { echo "$USAGE" >&2; exit 1; }
        country=${2^^}
        [[ $country =~ $COUNTRY_PATTERN ]] || { echo "Invalid country: $2 (expected a two-letter ISO 3166-1 code)" >&2; exit 1; }
        shift 2
        ;;
      --*)
        echo "$USAGE" >&2
        exit 1
        ;;
      *)
        if [[ -z $coords ]]; then
          coords=$1
        else
          echo "$USAGE" >&2
          exit 1
        fi
        shift
        ;;
    esac
  done
  if [[ -n $coords ]]; then
    [[ $coords =~ $COORDS_PATTERN ]] || { echo "Invalid coordinates: $coords (expected lat,lon)" >&2; exit 1; }
    location=$(jq -en --arg name "$name" --arg country "$country" --argjson latitude "${coords%,*}" --argjson longitude "${coords#*,}" \
      '{$name, $latitude, $longitude} + (if $country == "" then {} else {$country} end) | select(-90 <= .latitude and .latitude <= 90 and -180 <= .longitude and .longitude <= 180)') ||
      { echo "Invalid coordinates: $coords (latitude -90 to 90, longitude -180 to 180)" >&2; exit 1; }
  else
    location=$(jq -n --arg name "$name" --arg country "$country" '{$name} + (if $country == "" then {} else {$country} end)') || exit 1
  fi
  mkdir -p "$(dirname "$LOC_FILE")"
  echo "$location" >"$LOC_FILE"
  ;;
--clear)
  rm -f "$LOC_FILE"
  ;;
*)
  echo "$USAGE" >&2
  exit 1
  ;;
esac
