#!/usr/bin/bash
# ABOUTME: Waybar module that checks for available package updates with caching.
# ABOUTME: Combines pacman repo updates (checkupdates) and AUR updates (paru -Qua).

CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/moonarch"
CACHE_FILE="$CACHE_DIR/waybar-updates"
PACMAN_DB="/var/lib/pacman/local"
MAX_AGE=3600

mkdir -p "$CACHE_DIR"

needs_refresh() {
    # No cache yet
    [[ ! -f "$CACHE_FILE" ]] && return 0

    # Pacman DB changed since last check (update was installed)
    [[ "$PACMAN_DB" -nt "$CACHE_FILE" ]] && return 0

    # Cache older than MAX_AGE
    local age=$(( $(date +%s) - $(stat -c %Y "$CACHE_FILE") ))
    [[ "$age" -ge "$MAX_AGE" ]] && return 0

    return 1
}

if needs_refresh; then
    repo_updates=$(checkupdates 2>/dev/null)
    repo_count=0
    if [[ -n "$repo_updates" ]]; then
        repo_count=$(echo "$repo_updates" | wc -l)
    fi

    aur_updates=""
    aur_count=0
    if command -v paru &>/dev/null; then
        aur_updates=$(paru -Qua 2>/dev/null)
        if [[ -n "$aur_updates" ]]; then
            aur_count=$(echo "$aur_updates" | wc -l)
        fi
    fi

    total=$((repo_count + aur_count))

    if [[ "$total" -eq 0 ]]; then
        echo "" > "$CACHE_FILE"
        exit 0
    fi

    # Build tooltip with package lists
    tooltip=""
    if [[ -n "$repo_updates" ]]; then
        tooltip+="Repo ($repo_count):"$'\n'"$repo_updates"
    fi
    if [[ -n "$aur_updates" ]]; then
        [[ -n "$tooltip" ]] && tooltip+=$'\n\n'
        tooltip+="AUR ($aur_count):"$'\n'"$aur_updates"
    fi

    jq --compact-output -n \
        --arg text "$total" \
        --arg alt "has-updates" \
        --arg tooltip "$tooltip" \
        --arg class "has-updates" \
        '{text: $text, alt: $alt, tooltip: $tooltip, class: $class}' > "$CACHE_FILE"
fi

# Output cached result (empty cache = no updates = module hidden)
cat "$CACHE_FILE"
