#!/bin/bash
set -euo pipefail

SCHEME="CableScreenshots"
RESET_SIMULATOR="${RESET_SIMULATOR:-1}"
APP_BUNDLE_ID="${APP_BUNDLE_ID:-app.voltplan.CableApp}"
UITEST_BUNDLE_ID="${UITEST_BUNDLE_ID:-com.yuzuhub.CableUITestsScreenshot}"

is_truthy() {
  case "$1" in
    1|true|TRUE|yes|YES|on|ON) return 0 ;;
    0|false|FALSE|no|NO|off|OFF|"") return 1 ;;
    *) return 0 ;;
  esac
}

DEVICE_MATRIX=(
  "iPad Pro Screenshot|26.0|ipad-pro-13-inch-m4"
  "iPhone 17 Pro Max|26.0|iphone-17-pro-max"
)

command -v xcparse >/dev/null 2>&1 || {
  echo "xcparse not found. Install with: brew install chargepoint/xcparse/xcparse" >&2
  exit 1
}

# Resolve a simulator UDID for the given device name and optional OS (e.g., 18.1)
resolve_udid() {
  local name="$1"; local os="$2"
  if [[ -n "$os" ]]; then
    # Prefer Shutdown state for a clean start
    xcrun simctl list devices | awk -v n="$name" -v o="$os" -F '[()]' \
      '$0 ~ n && $0 ~ o && /Shutdown/ {print $2; exit}'
  else
    xcrun simctl list devices | awk -v n="$name" -F '[()]' \
      '$0 ~ n && /Shutdown/ {print $2; exit}'
  fi
}

for device_entry in "${DEVICE_MATRIX[@]}"; do
  IFS='|' read -r DEVICE_NAME DEVICE_RUNTIME DEVICE_SLUG <<<"$device_entry"
  echo "=== Device: $DEVICE_NAME (runtime: ${DEVICE_RUNTIME:-auto}) ==="

  for lang in de fr en es nl; do
    echo "Resetting simulator for a clean start..."
    UDID=$(resolve_udid "$DEVICE_NAME" "$DEVICE_RUNTIME")
    if [[ -z "$UDID" ]]; then
      UDID=$(xcrun simctl list devices | awk -v n="$DEVICE_NAME" -F '[()]' '$0 ~ n {print $2; exit}')
    fi
    if [[ -z "$UDID" ]]; then
      echo "Could not resolve UDID for $DEVICE_NAME" >&2; exit 1
    fi

    xcrun simctl shutdown "$UDID" || true
    if is_truthy "$RESET_SIMULATOR"; then
      xcrun simctl erase "$UDID"
    else
      for bundle in "$APP_BUNDLE_ID" "$UITEST_BUNDLE_ID"; do
        if [[ -n "$bundle" ]]; then
          xcrun simctl terminate "$UDID" "$bundle" || true
          xcrun simctl uninstall "$UDID" "$bundle" || true
        fi
      done
    fi
    echo "Running screenshots for $lang"
    region=$(echo "$lang" | tr '[:lower:]' '[:upper:]')

    UDID=$(resolve_udid "$DEVICE_NAME" "$DEVICE_RUNTIME")
    if [[ -z "$UDID" ]]; then
      UDID=$(xcrun simctl list devices | awk -v n="$DEVICE_NAME" -F '[()]' '$0 ~ n {print $2; exit}')
    fi
    if [[ -z "$UDID" ]]; then
      echo "Could not resolve UDID for $DEVICE_NAME" >&2; exit 1
    fi

    xcrun simctl boot "$UDID" || true
    xcrun simctl spawn "$UDID" defaults write 'Apple Global Domain' AppleLanguages -array "$lang"
    xcrun simctl spawn "$UDID" defaults write 'Apple Global Domain' AppleLocale "${lang}_${region}"
    xcrun simctl shutdown "$UDID" || true
    xcrun simctl boot "$UDID"
    xcrun simctl status_bar booted override \
      --time "9:41" \
      --batteryState charged --batteryLevel 100 \
      --wifiBars 3
 

    bundle="results-${DEVICE_SLUG}-${lang}.xcresult"
    outdir="Shots/Screenshots/${DEVICE_SLUG}/$lang"
    rm -rf "$bundle" "$outdir"
    mkdir -p "$outdir"

    xcodebuild test \
      -scheme "$SCHEME" \
      -destination "id=$UDID" \
      -resultBundlePath "$bundle"

    xcparse screenshots "$bundle" "$outdir"
    echo "Exported screenshots to $outdir"
    xcrun simctl shutdown "$UDID" || true
  done
done
