#!/usr/bin/env bash

# Directory of this script
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

JSON_URL="https://stat.ink/@M_Budget/spl3/index.json"
IMG_BASE="https://s3-img-gen.stats.ink/results/en-GB"
OUT_FILE="$SCRIPT_DIR/results.jpg"

# Get latest ID
ID=$(curl -s "$JSON_URL" | jq -r '.[0].id')

# Validate ID
if [ -z "$ID" ] || [ "$ID" = "null" ]; then
    echo "Failed to retrieve latest ID"
    exit 1
fi

IMG_URL="$IMG_BASE/$ID.jpg"

echo "Latest ID: $ID"
echo "Downloading $IMG_URL"

# Download and overwrite results.jpg
curl -L -s -o "$OUT_FILE" "$IMG_URL"

echo "Saved to $OUT_FILE"
