#!/bin/bash

set -Eeu -o pipefail

# Improved weather script for i3status-rust using JSON API
# Based on the original weather script but optimized for Sway/i3status-rust

# Location (defaults to Pärnu as in your original script)
VALUE_WEATHER_LOCATION=${weather_location:-"Pärnu"}
VALUE_WEATHER_ERROR_MESSAGE=${error_message:-"⛔"}

# Determine units to use for temperature
# We don't supply a default here because wttr.in is "smart" enough to choose for us
WEATHER_UNIT=${weather_unit:-""}
if [ -n "${WEATHER_UNIT}" ]; then
    WEATHER_UNIT="&${WEATHER_UNIT}"
fi

# Use JSON API to get all data in a single request
VALUE_FETCH_WEATHER_URL="https://wttr.in/${VALUE_WEATHER_LOCATION}?format=j1"

# Get weather data using JSON API
WEATHER_JSON=$(curl -sS "$VALUE_FETCH_WEATHER_URL" 2>/dev/null || echo "{}")

# Check for errors
if echo "$WEATHER_JSON" | grep -q "Unknown location"; then
    echo "${VALUE_WEATHER_ERROR_MESSAGE}"
    exit 0
fi

# Extract data using jq (should be available on most systems)
if command -v jq &>/dev/null; then
    # Extract current weather condition and temperature
    WEATHER_CONDITION=$(echo "$WEATHER_JSON" | jq -r '.current_condition[0].weatherDesc[0].value' 2>/dev/null || echo "")
    TEMP_C=$(echo "$WEATHER_JSON" | jq -r '.current_condition[0].temp_C' 2>/dev/null || echo "")
    
    # Extract sunrise and sunset times
    SUNRISE=$(echo "$WEATHER_JSON" | jq -r '.weather[0].astronomy[0].sunrise' 2>/dev/null || echo "")
    SUNSET=$(echo "$WEATHER_JSON" | jq -r '.weather[0].astronomy[0].sunset' 2>/dev/null || echo "")
    
    # Convert to simple format if we have data
    if [ -n "$WEATHER_CONDITION" ] && [ -n "$TEMP_C" ]; then
        # Map weather conditions to icons (simplified)
        case "$WEATHER_CONDITION" in
            *"Sunny"*|*"Clear"*) ICON="☀️";;
            *"Partly cloudy"*|*"Cloudy"*) ICON="⛅";;
            *"Overcast"*) ICON="☁️";;
            *"Rain"*|*"Drizzle"*) ICON="🌧️";;
            *"Snow"*) ICON="❄️";;
            *"Thunder"*) ICON="⛈️";;
            *"Fog"*|*"Mist"*) ICON="🌫️";;
            *) ICON="🌤️";;
        esac
        
        WEATHER="${ICON} ${TEMP_C}°C"
        
        # Format sunrise/sunset times (convert from "09:10 AM" to "09:10")
        if [ -n "$SUNRISE" ] && [ -n "$SUNSET" ]; then
            # Remove AM/PM and convert to 24-hour format
            SUNRISE_24=$(echo "$SUNRISE" | sed 's/ AM//;s/ PM//;s/^0//' | awk -F: '{if($1==12) print "00:"$2; else if($1<12) print $1":"$2; else print $1":"$2}')
            SUNSET_24=$(echo "$SUNSET" | sed 's/ AM//;s/ PM//;s/^0//' | awk -F: '{if($1==12) print "00:"$2; else if($1<12) print $1":"$2; else print $1":"$2}')
            
            # Remove leading zeros from hours for consistency
            SUNRISE_24=$(echo "$SUNRISE_24" | sed 's/^0//')
            SUNSET_24=$(echo "$SUNSET_24" | sed 's/^0//')
            
            SUNRISE_SUNSET_TEXT=" (${SUNRISE_24}-${SUNSET_24})"
        else
            SUNRISE_SUNSET_TEXT=""
        fi
        
        # Output for i3status-rust (plain text)
        echo "${WEATHER}${SUNRISE_SUNSET_TEXT}"
    else
        echo "${VALUE_WEATHER_ERROR_MESSAGE}"
    fi
else
    # Fallback to original method if jq is not available
    echo "⚠️ jq not found, using fallback method"
    
    # Get basic weather data
    VALUE_WEATHER_FORMAT=${weather_format:-"%c%f"}
    VALUE_WEATHER_FORMAT="?format=${VALUE_WEATHER_FORMAT}"
    WEATHER=$(curl -sS "https://wttr.in/${VALUE_WEATHER_LOCATION}${VALUE_WEATHER_FORMAT}${WEATHER_UNIT}" 2>/dev/null || echo "${VALUE_WEATHER_ERROR_MESSAGE}")
    
    # Get sunrise/sunset data
    VALUE_SUNSET_SUNRISE_FORMAT="?format=%S-%s"
    SUNRISE_SUNSET=$(curl -sS "https://wttr.in/${VALUE_WEATHER_LOCATION}${VALUE_SUNSET_SUNRISE_FORMAT}${WEATHER_UNIT}" 2>/dev/null || echo "")
    
    if [ -n "$SUNRISE_SUNSET" ]; then
        SUNRISE_VALUE=$(echo ${SUNRISE_SUNSET} | cut -c 1-5)
        SUNSET_VALUE=$(echo ${SUNRISE_SUNSET} | cut -c 7-11)
        SUNRISE_SUNSET_TEXT=" (${SUNRISE_VALUE}-${SUNSET_VALUE})"
    else
        SUNRISE_SUNSET_TEXT=""
    fi
    
    # Check for errors
    if echo "${WEATHER}" | grep -q -P "Unknown\slocation"; then
        WEATHER=${VALUE_WEATHER_ERROR_MESSAGE}
    fi
    
    # Output for i3status-rust (plain text)
    echo "${WEATHER}${SUNRISE_SUNSET_TEXT}"
fi

# Handle click events (for i3status-rust custom block)
if [ "${BLOCK_BUTTON:-}" = "1" ]; then
    # Left click - show detailed weather using JSON
    DETAILED_WEATHER=$(curl -sS "https://wttr.in/${VALUE_WEATHER_LOCATION}?format=%l:+%c+%f+%h+%p+%P+%m+%w+%S-%s" 2>/dev/null || echo "${VALUE_WEATHER_ERROR_MESSAGE}")
    notify-send "Weather Details" "$DETAILED_WEATHER" -t 10000
elif [ "${BLOCK_BUTTON:-}" = "3" ]; then
    # Right click - open weather website
    xdg-open "https://wttr.in/${VALUE_WEATHER_LOCATION}" >/dev/null 2>&1 &
fi