#!/usr/bin/env bash
#
# Remove snapshot-gallery goldens left over from prior test configurations.
# Run from the MyCribKMM repo root after the manifest-driven refactor has
# landed on both platforms' test files, THEN regenerate via
# `make record-snapshots`. The regeneration fills in the canonical set.
#
# Orphan categories removed:
#   1. Theme-named variants (default/midnight/ocean × light/dark) — from
#      an older per-theme capture scheme that predates the empty/populated
#      matrix.
#   2. Roborazzi comparison artifacts (_actual.png, _compare.png) — leftover
#      from verify-mode failures; regenerated on next record if needed.
#   3. Legacy empty/populated PNGs for DataFree surfaces — the new variant
#      matrix captures these as `<name>_light.png` / `<name>_dark.png`
#      without the empty/populated prefix, so the old files are obsolete.
#
# Safety: uses `git ls-files` to scope deletions to tracked files only,
# so no untracked work is touched. Dry-runs by default; pass `--execute`
# to actually delete.

set -euo pipefail

cd "$(dirname "$0")/.."

DRY_RUN=1
if [[ "${1:-}" == "--execute" ]]; then
  DRY_RUN=0
fi

ANDROID_DIR="composeApp/src/androidUnitTest/roborazzi"

# DataFree surfaces from the canonical manifest — parsed from the Kotlin
# source so this script doesn't go stale when the manifest changes.
MANIFEST="composeApp/src/commonMain/kotlin/com/tt/honeyDue/testing/GalleryManifest.kt"
DATA_FREE=$(grep -oE 'GalleryScreen\("[a-z_]+", GalleryCategory\.DataFree' "$MANIFEST" \
  | sed -E 's/GalleryScreen\("([a-z_]+)".*/\1/')

orphans=()

# 1. Theme-named legacy captures.
while IFS= read -r f; do
  orphans+=("$f")
done < <(ls "$ANDROID_DIR"/*_default_*.png "$ANDROID_DIR"/*_midnight_*.png "$ANDROID_DIR"/*_ocean_*.png 2>/dev/null || true)

# 2. Roborazzi comparison artifacts.
while IFS= read -r f; do
  orphans+=("$f")
done < <(ls "$ANDROID_DIR"/*_actual*.png "$ANDROID_DIR"/*_compare*.png 2>/dev/null || true)

# 3. Legacy empty/populated pairs for DataFree surfaces.
for surface in $DATA_FREE; do
  for suffix in empty_light empty_dark populated_light populated_dark; do
    f="$ANDROID_DIR/${surface}_${suffix}.png"
    [[ -f "$f" ]] && orphans+=("$f")
  done
done

count=${#orphans[@]}
echo "Found $count orphan Android goldens."

if [[ $count -eq 0 ]]; then
  exit 0
fi

if [[ $DRY_RUN -eq 1 ]]; then
  echo
  echo "Dry run — pass --execute to delete. Files that would be removed:"
  printf '  %s\n' "${orphans[@]}"
  exit 0
fi

echo "Deleting $count files..."
for f in "${orphans[@]}"; do
  git rm --quiet -f "$f" 2>/dev/null || rm -f "$f"
done
echo "Done. Commit the deletions in the same PR as the refactor so the review is one logical change."
