#!/usr/bin/env bash
# run-garment-qa: drive the chromakey garment-clipping QA harness (T-1089).
#
# Usage:  tooling/garment-qa/run-garment-qa [config.json]
#   config.json defaults to tooling/garment-qa/configs/peasant.json
#
# Step 1 launches Godot on the client project with the capture scene, pointing it
# at the config via GARMENT_QA_CONFIG. Step 2 runs the pixel analyzer over the PNGs
# the scene wrote. Both steps are deliberately kept to a single command each.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

CONFIG="${1:-$SCRIPT_DIR/configs/peasant.json}"
if [[ ! -f "$CONFIG" ]]; then
    echo "run-garment-qa: config not found: $CONFIG" >&2
    exit 2
fi

GODOT="${GODOT:-$HOME/bin/godot4}"
if [[ ! -x "$GODOT" ]]; then
    GODOT="$(command -v godot4 || command -v godot || true)"
fi
if [[ -z "$GODOT" ]]; then
    echo "run-garment-qa: godot binary not found (set GODOT=/path/to/godot4)" >&2
    exit 3
fi

PY="$REPO_ROOT/.venv/bin/python"
[[ -x "$PY" ]] || PY="python3"

SCENE="res://tools/garment_qa/chromakey_scene.tscn"

echo "run-garment-qa: config = $CONFIG"
echo "run-garment-qa: godot  = $GODOT"

# Step 1 — capture. Needs a display; use xvfb-run when running headless.
export GARMENT_QA_CONFIG="$CONFIG"
if [[ -n "${DISPLAY:-}" ]]; then
    "$GODOT" --path "$REPO_ROOT/client" --rendering-driver opengl3 "$SCENE"
else
    xvfb-run -a "$GODOT" --path "$REPO_ROOT/client" --rendering-driver opengl3 "$SCENE"
fi

# Step 2 — analyze.
"$PY" "$SCRIPT_DIR/analyze_captures.py" --config "$CONFIG"
