#!/bin/bash
# WebDriverAgent bootstrap for iOS simulator testing with @midscene/ios.
# Uses Appium's prebuilt simulator WDA — no signing or Xcode project needed.
#
#   ./scripts/wda.sh setup    # download + unzip prebuilt WDA (one-time)
#   ./scripts/wda.sh start    # boot simulator, install + launch WDA, wait for :8100
#   ./scripts/wda.sh status   # check WDA health endpoint
set -euo pipefail

WDA_VERSION="v16.11.4"
WDA_ZIP_URL="https://github.com/appium/WebDriverAgent/releases/download/${WDA_VERSION}/WebDriverAgentRunner-Build-Sim-arm64.zip"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENDOR_DIR="${SCRIPT_DIR}/../vendor/wda"
WDA_BUNDLE_ID="com.facebook.WebDriverAgentRunner.xctrunner"
WDA_PORT="${WDA_PORT:-8100}"
SIM_NAME="${SIM_NAME:-iPhone 17 Pro}"

find_runner_app() {
  find "${VENDOR_DIR}" -maxdepth 4 -name "WebDriverAgentRunner-Runner.app" -type d | head -1
}

cmd_setup() {
  mkdir -p "${VENDOR_DIR}"
  if [ -n "$(find_runner_app)" ]; then
    echo "WDA already present: $(find_runner_app)"
    return 0
  fi
  echo "Downloading prebuilt WDA ${WDA_VERSION} (simulator, arm64)..."
  curl -fL -o "${VENDOR_DIR}/wda-sim.zip" "${WDA_ZIP_URL}"
  unzip -qo "${VENDOR_DIR}/wda-sim.zip" -d "${VENDOR_DIR}"
  echo "WDA ready: $(find_runner_app)"
}

cmd_start() {
  local app
  app="$(find_runner_app)"
  if [ -z "${app}" ]; then
    cmd_setup
    app="$(find_runner_app)"
  fi

  local udid
  udid="$(xcrun simctl list devices booted | grep -oE '[0-9A-F-]{36}' | head -1 || true)"
  if [ -z "${udid}" ]; then
    echo "Booting simulator: ${SIM_NAME}"
    udid="$(xcrun simctl list devices available | grep "${SIM_NAME} (" | grep -oE '[0-9A-F-]{36}' | head -1)"
    xcrun simctl boot "${udid}"
    open -a Simulator
  fi
  echo "Using simulator ${udid}"

  xcrun simctl install "${udid}" "${app}"
  xcrun simctl launch "${udid}" "${WDA_BUNDLE_ID}"

  echo -n "Waiting for WDA on :${WDA_PORT} "
  for _ in $(seq 1 30); do
    if curl -sf "http://localhost:${WDA_PORT}/status" >/dev/null 2>&1; then
      echo; echo "WDA is ready: http://localhost:${WDA_PORT}/status"
      return 0
    fi
    echo -n "."
    sleep 1
  done
  echo; echo "ERROR: WDA did not come up on :${WDA_PORT}" >&2
  exit 1
}

cmd_status() {
  curl -s "http://localhost:${WDA_PORT}/status" | head -c 400; echo
}

case "${1:-}" in
  setup)  cmd_setup ;;
  start)  cmd_start ;;
  status) cmd_status ;;
  *) echo "Usage: $0 {setup|start|status}"; exit 1 ;;
esac
