#!/usr/bin/env bash
# Updates everything from stat.ink:
#   1. index.json             - your latest battles, via the stat.ink v3 API
#   2. results.jpg            - result image of the latest battle
#   3. <mode>_xpower.png      - latest X Power per mode (modes not in index.json keep their old image)
#
# Needs your stat.ink API key (stat.ink -> Profile and Settings -> API key), either in
# $STATINK_API_KEY or in the file $STATINK_KEY_FILE (default: ~/.statink_api_key).
# Don't put the key file inside the web root.

set -euo pipefail

DIR="$(cd "$(dirname "$0")" && pwd)"
JSON_FILE="$DIR/index.json"
API="https://stat.ink/api/v3"
IMG_BASE="https://s3-img-gen.stats.ink/results/en-GB"
BATTLES=10   # how many of the newest battles index.json contains

KEY_FILE="${STATINK_KEY_FILE:-$HOME/.statink_api_key}"
API_KEY="${STATINK_API_KEY:-}"
if [ -z "$API_KEY" ] && [ -r "$KEY_FILE" ]; then
    API_KEY="$(tr -d '[:space:]' < "$KEY_FILE")"
fi
if [ -z "$API_KEY" ]; then
    echo "No API key: set STATINK_API_KEY or create $KEY_FILE"
    exit 1
fi

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

# ---------------------------------------------------------------------------
# 1. index.json
# ---------------------------------------------------------------------------

# UUIDs of your recent battles, newest first
if ! curl -sf -H "Authorization: Bearer $API_KEY" "$API/s3s/uuid-list" -o "$TMP_DIR/uuids.json"; then
    echo "Failed to fetch UUID list (wrong API key?)"
    exit 1
fi

# Reuse battles we already have, battle data doesn't change after upload
if jq -e . "$JSON_FILE" >/dev/null 2>&1; then
    cp "$JSON_FILE" "$TMP_DIR/old.json"
else
    echo '[]' > "$TMP_DIR/old.json"
fi

# uuid-list returns the client (s3s) UUIDs, stored as .uuid in the battle JSON.
# The API only serves battles by stat.ink's own .id, and the only way to map one
# to the other is to "re-upload" just the UUID: stat.ink then finds the existing
# battle and returns its id in X-Battle-ID without creating anything.
mkdir "$TMP_DIR/battles"
NEW=0
for UUID in $(jq -r '.[]' "$TMP_DIR/uuids.json" | head -n "$BATTLES"); do
    if jq -e --arg u "$UUID" 'any(.[]; .uuid == $u)' "$TMP_DIR/old.json" >/dev/null; then
        continue
    fi

    if ! curl -sf -o /dev/null -D "$TMP_DIR/headers" \
        -H "Authorization: Bearer $API_KEY" -H "Content-Type: application/json" \
        -d "{\"uuid\":\"$UUID\"}" "$API/battle"; then
        echo "Warning: failed to look up battle $UUID"
        continue
    fi
    ID=$(awk -F': *' 'tolower($1)=="x-battle-id" {print $2}' "$TMP_DIR/headers" | tr -d '\r')
    FOUND=$(awk -F': *' 'tolower($1)=="x-found" {print $2}' "$TMP_DIR/headers" | tr -d '\r')
    if [ -z "$ID" ]; then
        echo "Warning: no battle id returned for $UUID"
        continue
    fi
    if [ "$FOUND" != "?1" ]; then
        # Shouldn't happen, but never leave an empty battle behind on stat.ink
        echo "Warning: $UUID was not found but created as $ID, deleting it again"
        curl -sf -o /dev/null -X DELETE -H "Authorization: Bearer $API_KEY" "$API/battle/$ID" \
            || echo "Warning: failed to delete $ID, please remove it manually on stat.ink"
        continue
    fi

    if curl -sf "$API/battle/$ID" -o "$TMP_DIR/battles/$ID.json"; then
        NEW=$((NEW + 1))
    else
        echo "Warning: failed to fetch battle $ID"
        rm -f "$TMP_DIR/battles/$ID.json"
    fi
done

# Merge old + new, newest first, write atomically
shopt -s nullglob
jq -s --argjson max "$BATTLES" '
    (.[0] + .[1:]) | unique_by(.id) | sort_by(-.end_at.time) | .[:$max]
' "$TMP_DIR/old.json" "$TMP_DIR"/battles/*.json > "$TMP_DIR/index.json"

if [ "$(jq length "$TMP_DIR/index.json")" -eq 0 ]; then
    echo "Result is empty, keeping old $JSON_FILE"
    exit 1
fi

cat "$TMP_DIR/index.json" > "$JSON_FILE"
echo "Fetched $NEW new battle(s), $(jq length "$JSON_FILE") in $JSON_FILE"

# ---------------------------------------------------------------------------
# 2. results.jpg
# ---------------------------------------------------------------------------

ID=$(jq -r '.[0].id' "$JSON_FILE")
IMG_URL="$IMG_BASE/$ID.jpg"
echo "Latest ID: $ID"
echo "Downloading $IMG_URL"

if curl -Lsf -o "$TMP_DIR/results.jpg" "$IMG_URL"; then
    cat "$TMP_DIR/results.jpg" > "$DIR/results.jpg"
    echo "Saved to $DIR/results.jpg"
else
    echo "Warning: failed to download result image, keeping old one"
fi

# ---------------------------------------------------------------------------
# 3. <mode>_xpower.png
# ---------------------------------------------------------------------------

jq -r '.[] |
  select((.x_power_after // .x_power_before) != null) |
  "\(.rule.key) \(.x_power_after // .x_power_before)"' "$JSON_FILE" \
| awk -v dir="$DIR" '

BEGIN{
    modes["hoko"]="rainmaker"
    modes["area"]="splatzones"
    modes["yagura"]="towercontrol"
    modes["asari"]="clamblitz"
}

{
    rule=$1
    power=$2
    mode=modes[rule]

    if(mode && !done[mode]){
        outfile=dir "/" mode "_xpower.png"

        # Transparent background with just the number
        cmd="convert -size 125x50 xc:none -gravity center -fill \"#ffc6de\" -pointsize 35" \
        " -annotate 0 \"" power "\" \"" outfile "\""

        system(cmd)
        done[mode]=1
        print "X Power " mode ": " power
    }

    if(length(done)==4)
        exit
}'
