#!/bin/bash

# Simple wrapper to run Maestro with env vars from .env file
# Workaround for Maestro's @filename syntax bug (treats values as flow paths)
#
# Usage: ./e2e/run-with-env.sh <flow-file-or-dir> <env-file> <platform> [maestro-args...]
# Example: ./e2e/run-with-env.sh e2e/flows/my-test.yml e2e/.env.dev android
# Example: ./e2e/run-with-env.sh e2e/flows e2e/.env.dev ios
# Example: ./e2e/run-with-env.sh e2e/flows e2e/.env.dev android --config e2e/config.yml
# Example: ./e2e/run-with-env.sh e2e/flows e2e/.env.dev ios --config e2e/config.yml

set -e

FLOW_PATH="$1"
ENV_FILE="$2"
PLATFORM="$3"
shift 3 || true

MEDIA_DIR="e2e/shared/pick-asset/assets"

if [ "$PLATFORM" == "android" ]; then
  APP_ID="com.humand.demo"
  if ! command -v adb &> /dev/null; then
    echo "Error: adb command not found. Please install Android SDK platform-tools."
    exit 1
  fi
  DEVICE_COUNT=$(adb devices | grep -v "List of devices" | grep -c "device$" || true)
  if [ "$DEVICE_COUNT" -eq 0 ]; then
    echo "Error: No Android device or emulator connected. Please connect a device or start an emulator."
    exit 1
  fi
  adb shell ls /sdcard/Download/document.pdf &> /dev/null || adb push "$MEDIA_DIR/document.pdf" /sdcard/Download/
  for media in "$MEDIA_DIR"/*.{mp4,jpg,jpeg,png,gif}; do
    [ -f "$media" ] || continue
    filename=$(basename "$media")
    if ! adb shell ls "/sdcard/DCIM/$filename" &> /dev/null; then
      adb push "$media" "/sdcard/DCIM/$filename"
      adb shell am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d "file:///sdcard/DCIM/$filename" > /dev/null
    fi
  done
elif [ "$PLATFORM" == "ios" ]; then
  APP_ID="com.Humand.Demo"
  BOOTED_UDIDS=$(xcrun simctl list devices booted | grep -oE '[0-9A-F-]{36}')
  if [ -z "$BOOTED_UDIDS" ]; then
    echo "Error: No booted iOS simulator found."
    exit 1
  fi
  for UDID in $BOOTED_UDIDS; do
    MARKER_FILE="/tmp/maestro_media_${UDID}"
    if [ ! -f "$MARKER_FILE" ]; then
      echo "Adding media to iOS simulator ($UDID)..."
      (shopt -s nullglob; xcrun simctl addmedia "$UDID" "$MEDIA_DIR"/*.{mp4,jpg,jpeg,png,gif})
      touch "$MARKER_FILE"
    fi
  done
else
  echo "Error: Invalid platform: $PLATFORM"
  exit 1
fi

if [ "$ENV_FILE" == "e2e/.env.dev" ]; then
  APP_ID="$APP_ID.dev"
elif [ "$ENV_FILE" == "e2e/.env.stg" ]; then
  APP_ID="$APP_ID.stg"
fi

echo "Running test with APP_ID: $APP_ID"

[ ! -f "$ENV_FILE" ] && { echo "Error: $ENV_FILE not found"; exit 1; }
[ ! -e "$FLOW_PATH" ] && { echo "Error: $FLOW_PATH not found"; exit 1; }

# Read env file and convert KEY=value lines to -e KEY=value format for maestro
# Ignores comments and empty lines
# Additional maestro args (like --config) are passed through
ENV_ARGS=$(grep -vE '^\s*(#|$)' "$ENV_FILE" | sed 's/^/-e /' | tr '\n' ' ')
eval "maestro test \"$FLOW_PATH\" $ENV_ARGS -e APP_ID=$APP_ID $*"
