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

MIN_DURATION_MS="${Q4_DEMO_MIN_DURATION_MS:-0}"

if [[ $# -lt 1 ]]; then
    echo "Usage: $0 <replay-directory> [fallback-directory ...]" >&2
    exit 2
fi
if [[ ! "${MIN_DURATION_MS}" =~ ^(0|[1-9][0-9]*)$ ]]; then
    echo "Q4_DEMO_MIN_DURATION_MS must be a non-negative integer" >&2
    exit 2
fi
command -v python3 >/dev/null 2>&1 || {
    echo "Required replay selector command is missing: python3" >&2
    exit 1
}

metadata_eligible() {
    python3 - "$1" "${MIN_DURATION_MS}" <<'PY'
import json
import sys

try:
    with open(sys.argv[1], encoding="utf-8-sig") as stream:
        metadata = json.load(stream)
except (OSError, UnicodeError, json.JSONDecodeError):
    raise SystemExit(1)

minimum = int(sys.argv[2])
duration = metadata.get("durationMs")
if metadata.get("complete") is not True:
    raise SystemExit(1)
if minimum > 0 and (isinstance(duration, bool) or not isinstance(duration, int) or duration < minimum):
    raise SystemExit(1)
PY
}

for replay_dir in "$@"; do
    [[ -d "${replay_dir}" ]] || continue

    mapfile -t candidates < <(
        find "${replay_dir}" -maxdepth 1 -type f -name '*.q4sd' -printf '%s %T@ %p\n' \
            | sort -k1,1nr -k2,2nr \
            | cut -d' ' -f3-
    )
    for candidate in "${candidates[@]}"; do
        [[ "$(head -c 4 -- "${candidate}")" == 'Q4SD' ]] || continue
        [[ -f "${candidate}.meta.json" ]] || continue
        metadata_eligible "${candidate}.meta.json" || continue
        realpath -- "${candidate}"
        exit 0
    done
done

exit 1
