#!/bin/bash

SYNC_INTERVAL=1800
SYNC_TIMESTAMP="/tmp/last_checkupdates_sync"
NO_ZERO_OUTPUT=false

now=$(date +%s)
last=$(cat "$SYNC_TIMESTAMP" 2>/dev/null || echo 0)
if (( now - last >= SYNC_INTERVAL )); then
    rm -rf "/tmp/checkup-db-$UID"
    checkupdates > /dev/null 2>&1
    echo "$now" > "$SYNC_TIMESTAMP"
fi

# Mapping: REPOS destino de cada paquete
declare -A update_repo_map
mapping=$(sudo pacman -Syuw --print-format '%r %n' --noconfirm | grep -v '^::' | grep -v '^descargando')
while read -r repo pkg; do
    [[ -z "$repo" || -z "$pkg" ]] && continue
    update_repo_map["$pkg"]="$repo"
done <<< "$mapping"

updates=$(checkupdates --nosync 2>/dev/null)
aur_updates=$(paru -Qua 2>/dev/null)

total_count=0
tooltip_lines=()

# OJO: este while debe ser así, ¡NUNCA uses tuberías aquí!
IFS=$'\n'
for line in $updates; do
    [[ -z "$line" ]] && continue
    pkg=$(awk '{print $1}' <<< "$line")
    old=$(awk '{print $2}' <<< "$line")
    new=$(awk '{print $4}' <<< "$line")
    repo="${update_repo_map[$pkg]}"
    [[ -z "$repo" ]] && repo="???"
    formatted=$(printf "%-15s %-30s %s → %s" "$repo" "$pkg" "$old" "$new")
    tooltip_lines+=("$formatted")
    ((total_count++))
done

# AUR
for line in $aur_updates; do
    [[ -z "$line" ]] && continue
    pkg=$(awk '{print $1}' <<< "$line")
    old=$(awk '{print $2}' <<< "$line")
    new=$(awk '{print $4}' <<< "$line")
    formatted=$(printf "%-15s %-30s %s → %s" "aur" "$pkg" "$old" "$new")
    tooltip_lines+=("$formatted")
    ((total_count++))
done

aur_rebuild=$(cat /tmp/aur_rebuild_count 2>/dev/null || echo 0)
if [[ "$aur_rebuild" -gt 0 ]]; then
    tooltip_lines+=("")
    tooltip_lines+=("️  $aur_rebuild paquetes AUR necesitan recompilación")
fi

if [[ "$total_count" -eq 0 && "$aur_rebuild" -eq 0 ]]; then
    if [[ "$NO_ZERO_OUTPUT" == true ]]; then
        echo '{"text": "", "tooltip": "Todo actualizado", "class": "updated", "alt": "updated"}'
    else
        echo '{"text": "0", "tooltip": "Todo actualizado", "class": "updated", "alt": "updated"}'
    fi
else
    tooltip=$(printf "%s\n" "${tooltip_lines[@]}" | jq -R -s '.')
    echo "{\"text\": \"$total_count\", \"tooltip\": $tooltip, \"class\": \"has-updates\", \"alt\": \"has-updates\"}"
fi

