#!/usr/bin/env bash
# grab-onboarding-screenshot.sh
#
# Zieht Android-Screenshots via adb + speichert mit Auto-Numbering damit
# nichts überschrieben wird. Pro <lang>/<dialog>-Combo wird die nächste
# freie Nummer XYZ gewählt → <dialog>-001.png, <dialog>-002.png, ...
#
# So kann man mehrere Steps der gleichen Flow capturen (z.B. VPN-Dialog
# vorher / nachher, A11y-Settings-Liste / -Toggle / -Confirm) und später
# in Ruhe entscheiden welche Files wir tatsächlich im Pre-Explainer zeigen.
#
# Usage:
#   ./grab-onboarding-screenshot.sh <lang> <dialog>
#   <lang>    = de | en | fr | ar (oder beliebig)
#   <dialog>  = freier Name (z.B. android-vpn-permission, android-a11y-step1,
#               android-a11y-toggle, ios-permission, etc.)
#
# Beispiele:
#   ./grab-onboarding-screenshot.sh de android-vpn-permission
#   ./grab-onboarding-screenshot.sh de android-vpn-permission  # → -002.png
#   ./grab-onboarding-screenshot.sh de android-a11y-overview
#   ./grab-onboarding-screenshot.sh en android-a11y-rebreak-toggle

set -euo pipefail

LANG="${1:-}"
DIALOG="${2:-}"

if [[ -z "$LANG" || -z "$DIALOG" ]]; then
  echo "Usage: $0 <lang> <dialog>"
  echo "  lang:   de | en | fr | ar (oder anderer Folder-Name)"
  echo "  dialog: freier Name (z.B. android-vpn-permission, android-a11y-step1)"
  exit 1
fi

# Validate lang nicht hart — User kann auch debug/misc/etc anlegen wenn nötig.
# Nur Sanity-Check: alphanum + dash + underscore.
if [[ ! "$LANG" =~ ^[a-zA-Z0-9_-]+$ ]]; then
  echo "Invalid lang/folder name: $LANG"; exit 1
fi
if [[ ! "$DIALOG" =~ ^[a-zA-Z0-9_-]+$ ]]; then
  echo "Invalid dialog name: $DIALOG"; exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARGET_DIR="$SCRIPT_DIR/../assets/onboarding/$LANG"
mkdir -p "$TARGET_DIR"

# Auto-Numbering: finde nächste freie ${DIALOG}-NNN.png
NEXT_NUM=1
while [[ -f "$TARGET_DIR/${DIALOG}-$(printf "%03d" $NEXT_NUM).png" ]]; do
  NEXT_NUM=$((NEXT_NUM + 1))
done
TARGET_FILE="$TARGET_DIR/${DIALOG}-$(printf "%03d" $NEXT_NUM).png"

if ! command -v adb >/dev/null 2>&1; then
  echo "adb nicht installiert. Brew: brew install --cask android-platform-tools"
  exit 1
fi

DEVICE_COUNT=$(adb devices | grep -c "^[a-zA-Z0-9].*device$" || true)
if [[ "$DEVICE_COUNT" -lt 1 ]]; then
  echo "Kein Android-Device verbunden. USB-Debugging an + adb devices checken."
  exit 1
fi

echo "→ pull screenshot to $TARGET_FILE"
adb exec-out screencap -p > "$TARGET_FILE"

if [[ -s "$TARGET_FILE" ]]; then
  SIZE=$(du -h "$TARGET_FILE" | cut -f1)
  COUNT=$(ls -1 "$TARGET_DIR/${DIALOG}-"*.png 2>/dev/null | wc -l | tr -d ' ')
  echo "✓ saved $SIZE → ${DIALOG}-$(printf "%03d" $NEXT_NUM).png ($COUNT total for this dialog)"
else
  echo "✗ screenshot empty — adb issue?"
  rm -f "$TARGET_FILE"
  exit 1
fi
