#!/usr/bin/env bash
# Cast-overlay descriptor (web/cast-overlay.js) for one replay: colours,
# races, rolling APM and hero timelines parsed from the replay bytes by
# tools/make-cast-descriptors.mjs, the live site's parsers. Written once
# to $W3CS_CAST_DIR/<id>.json and served at /cast/<id>.json by w3cs-web.
# Best effort by design: a parser failure only costs the overlay extras
# (the page falls back to the catalog's roster), never the session.
#
# Usage: ensure-cast-descriptor.sh <replay.w3g> <replay id>
set -uo pipefail
REPLAY=${1:?replay file}
ID=${2:?replay id}
DIR=${W3CS_CAST_DIR:-}
TOOL=${W3CS_CAST_TOOL:-}
[[ -n "$DIR" && -n "$TOOL" && -f "$REPLAY" ]] || exit 0
# Staged demo ids ship static descriptors in app/cast; only catalog sha1s.
[[ "$ID" =~ ^[0-9a-f]{40}$ ]] || exit 0
OUT="$DIR/$ID.json"
[[ -s "$OUT" ]] && exit 0
command -v node >/dev/null || { echo "cast descriptor: node is missing" >&2; exit 0; }
mkdir -p "$DIR"
timeout "${W3CS_CAST_TIMEOUT:-45}" node "$TOOL" --replay "$REPLAY" --id "$ID" --out "$OUT" \
  || echo "cast descriptor: failed for $ID (overlay shows the catalog roster)" >&2
exit 0
