#!/usr/bin/env bash
set -euo pipefail

cd /home/rbatty/.local/share/psopeeps_site

out="site/generated/hardcore-leaderboard-points.json"
mkdir -p "$(dirname "$out")"

tmp="$(mktemp "${out}.tmp.XXXXXX")"
trap 'rm -f "$tmp"' EXIT

docker exec -i psopeeps-web-app python - <<'PY' > "$tmp"
from app import _hc_combined_payload, _hc_points_row
from datetime import datetime, timezone
import json

combined, errors = _hc_combined_payload()

rows = []
for source_row in combined:
    points_row = _hc_points_row(source_row)

    rows.append({
        "PlayerName": (
            points_row.get("PlayerName")
            or points_row.get("CharacterName")
            or source_row.get("character_name")
            or ""
        ),
        "Points": int(points_row.get("Points") or points_row.get("TotalPoints") or 0),
        "Class": (
            points_row.get("Class")
            or source_row.get("character_class")
            or ""
        ),
        "SecID": (
            points_row.get("SecID")
            or source_row.get("section_id")
            or ""
        ),
        "Kills": int(points_row.get("Kills") or points_row.get("TotalKills") or source_row.get("total_enemies_killed") or 0),
        "PlayTimeSeconds": int(points_row.get("PlayTimeSeconds") or source_row.get("play_time_seconds") or 0),
        "Alive": bool(points_row.get("Alive", True)),
        "Level": int(points_row.get("Level") or source_row.get("level") or 0),
        "TotalEXP": int(points_row.get("TotalEXP") or source_row.get("total_exp") or 0),
    })

rows.sort(key=lambda r: r["Points"], reverse=True)

payload = {
    "generated_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
    "stale_after_seconds": 600,
    "errors": errors,
    "rows": rows[:100],
}

print(json.dumps(payload, separators=(",", ":")))
PY

python3 -m json.tool "$tmp" >/dev/null
mv -f "$tmp" "$out"
trap - EXIT
