#!/usr/bin/env bash
#
# record_snapshots.sh — regenerate every parity-gallery golden in one pass.
#
# Use this after an intentional UI change (new color token, redesigned
# layout, etc.) so the committed baseline matches the new look. Reviewers
# see the PNG diff alongside your code change in the PR — that dual-diff
# is the whole point of the parity gallery.
#
# Usage
# -----
#   ./scripts/record_snapshots.sh                # iOS + Android
#   ./scripts/record_snapshots.sh --ios-only
#   ./scripts/record_snapshots.sh --android-only
#
# Pipeline
# --------
#   1. (Android) `./gradlew :composeApp:recordRoborazziDebug`
#   2. (iOS)     Delete iosApp/HoneyDueTests/__Snapshots__/SnapshotGalleryTests,
#                set SNAPSHOT_TESTING_RECORD=1, run xcodebuild test for
#                SnapshotGalleryTests. The env var is read by
#                SnapshotGalleryTests.swift to flip SnapshotTesting.record
#                between `.missing` (default — safe) and `.all` (overwrite).
#   3. Run `scripts/optimize_goldens.sh` across both golden directories to
#      shrink the fresh PNGs.
#
set -euo pipefail

cd "$(dirname "$0")/.."
ROOT="$(pwd)"

platform="both"
for arg in "$@"; do
    case "$arg" in
        --ios-only)     platform="ios" ;;
        --android-only) platform="android" ;;
        -h|--help)
            sed -n '3,18p' "$0"
            exit 0
            ;;
        *)
            echo "usage: $0 [--ios-only|--android-only]" >&2
            exit 1
            ;;
    esac
done

# ---------- Android ----------
if [ "$platform" = "both" ] || [ "$platform" = "android" ]; then
    echo "==> Recording Android goldens…"
    ./gradlew :composeApp:recordRoborazziDebug
fi

# ---------- iOS ----------
if [ "$platform" = "both" ] || [ "$platform" = "ios" ]; then
    echo "==> Recording iOS goldens…"
    rm -rf iosApp/HoneyDueTests/__Snapshots__/SnapshotGalleryTests
    (
        cd iosApp
        # SNAPSHOT_TESTING_RECORD=1 flips SnapshotTesting.isRecording to
        # `.all` (see SnapshotGalleryTests.swift).
        SNAPSHOT_TESTING_RECORD=1 xcodebuild test \
            -project honeyDue.xcodeproj \
            -scheme HoneyDue \
            -destination "${IOS_SIM_DESTINATION:-platform=iOS Simulator,name=iPhone 17,OS=latest}" \
            -only-testing:HoneyDueTests/SnapshotGalleryTests \
            2>&1 | tail -30
    )
fi

# ---------- Optimize ----------
echo "==> Optimizing PNGs…"
"$ROOT/scripts/optimize_goldens.sh"

# ---------- Parity HTML (P4 follow-up) ----------
if [ -x "$ROOT/scripts/build_parity_gallery.py" ]; then
    echo "==> Regenerating parity HTML gallery…"
    python3 "$ROOT/scripts/build_parity_gallery.py"
else
    echo "==> (parity HTML generator not yet present — skipping)"
fi

echo "==> Done. Review the PNG diff with your code change before committing."
