#!/usr/bin/env bash

interval=5   # seconds between updates

while true; do
    data=$(pueue status --json)

    queued=$(jq '.tasks | map(select(.status=="Queued")) | length' <<< "$data")
    running=$(jq '.tasks | map(select(.status=="Running")) | length' <<< "$data")
    total=$(jq '.tasks | length' <<< "$data")

    # average duration of finished tasks (seconds)
    avg=$(jq '.tasks
                | map(select(.start != null and .end != null)
                      | ((.end[0:19] + "Z") | fromdate) - ((.start[0:19] + "Z") | fromdate))
                | if length > 0 then add / length else 0 end' <<< "$data")

    clear
    echo "Queued:  $queued"
    echo "Running: $running"
    echo "Total:   $total"

    # Only calculate ETA if avg > 0
    if (( $(echo "$avg > 0" | bc -l) )); then
        remaining=$((queued + running))
        eta_seconds=$(echo "$remaining * $avg" | bc -l)
        finish_time=$(date -d "@$(($(date +%s) + ${eta_seconds%.*}))" +"%Y-%m-%d %H:%M:%S")
        printf "Average duration: %.2fs\n" "$avg"
        printf "ETA: ~%.0fs (finishing around %s)\n" "$eta_seconds" "$finish_time"
    else
        echo "ETA: Not enough finished jobs in history yet."
    fi

    sleep $interval
done

