#!/usr/bin/env bash
# Rebuild arena-elo-animated-current.html from fresh data.
#
# Pulls the latest LMArena leaderboard parquet, extracts the "overall"
# category as (date, model, elo) triples, inlines d3.min.js, and writes
# a fully self-contained HTML page. Requires: curl, duckdb.
#
# Run from this directory:  ./build.sh

set -euo pipefail
cd "$(dirname "$0")"

PARQUET_URL="https://huggingface.co/datasets/lmarena-ai/leaderboard-dataset/resolve/main/text/full-00000-of-00001.parquet"
D3_URL="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"
PARQUET=data/leaderboard.parquet
DATA_JSON=data/arena-overall.json
D3=data/d3.min.js
OUT=arena-elo-animated-current.html

mkdir -p data

echo "fetch parquet"
curl -sSL --fail "$PARQUET_URL" -o "$PARQUET"

echo "fetch d3"
[ -f "$D3" ] || curl -sSL --fail "$D3_URL" -o "$D3"

echo "extract overall category as JSON"
duckdb -c "COPY (
    SELECT leaderboard_publish_date AS date,
           model_name                AS model,
           rating                    AS elo
    FROM '$PARQUET'
    WHERE category = 'overall'
    ORDER BY leaderboard_publish_date, rating DESC
) TO '$DATA_JSON' (FORMAT JSON, ARRAY true);"

LAST_DATE=$(duckdb -noheader -list -c "SELECT MAX(leaderboard_publish_date) FROM '$PARQUET' WHERE category='overall';" | tail -1)
ROW_COUNT=$(duckdb -noheader -list -c "SELECT COUNT(*) FROM '$PARQUET' WHERE category='overall';" | tail -1)
DATE_COUNT=$(duckdb -noheader -list -c "SELECT COUNT(DISTINCT leaderboard_publish_date) FROM '$PARQUET' WHERE category='overall';" | tail -1)

echo "stitch HTML  (last_date=$LAST_DATE  rows=$ROW_COUNT  dates=$DATE_COUNT)"

{
    sed "s|@@LAST_DATE@@|$LAST_DATE|g; s|@@ROW_COUNT@@|$ROW_COUNT|g; s|@@DATE_COUNT@@|$DATE_COUNT|g" tmpl/head.html
    echo '<script>'
    cat "$D3"
    echo
    echo 'const ARENA_DATA = '
    cat "$DATA_JSON"
    echo ';'
    cat tmpl/animate.js
    echo '</script>'
    cat tmpl/foot.html
} > "$OUT"

echo "wrote $OUT  ($(wc -c <"$OUT") bytes)"

# Mirror to public/ so it's served at streetlight.jakesimonds.com/arena-elo-animated-current/
# (Worker maps /<slug>/ → public/<slug>/<slug>.html with no auth.)
PUBLIC_DIR=../../../public/arena-elo-animated-current
mkdir -p "$PUBLIC_DIR"
cp "$OUT" "$PUBLIC_DIR/arena-elo-animated-current.html"
echo "mirrored to $PUBLIC_DIR/arena-elo-animated-current.html"
