#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=common.sh
source "${SCRIPT_DIR}/common.sh"

if [ "$(detect_os)" != "macos" ]; then
  log_warn "Apple SDK and simulator checks require macOS; skipping on $(detect_os)."
  exit 0
fi

APPLE_STRICT="${EUV_APPLE_STRICT:-0}"
INSTALL_WATCHOS="${EUV_APPLE_INSTALL_WATCHOS:-0}"
WATCHOS_TIMEOUT="${EUV_APPLE_WATCHOS_DOWNLOAD_TIMEOUT:-300}"

DEV_DIR="$(xcode-select -p 2>/dev/null || true)"
log_info "Active developer directory: ${DEV_DIR:-missing}"
log_info "macOS SDK: $(xcrun --sdk macosx --show-sdk-path 2>/dev/null || echo missing)"

if ! xcrun simctl list runtimes >/dev/null 2>&1; then
  if [ -d "/Applications/Xcode.app/Contents/Developer" ]; then
    log_warn "Xcode.app is installed at /Applications/Xcode.app, but xcode-select points to '${DEV_DIR}'."
    log_warn "Run: sudo xcode-select -s /Applications/Xcode.app/Contents/Developer"
  else
    log_warn "Full Xcode.app is not installed (CommandLineTools only)."
    log_warn "iOS, iPadOS, and watchOS Simulators require Xcode from the Mac App Store or https://developer.apple.com/xcode/."
    log_warn "After installing Xcode.app, run: sudo xcode-select -s /Applications/Xcode.app/Contents/Developer && sudo xcodebuild -runFirstLaunch"
  fi
  if [ "${APPLE_STRICT}" = "1" ]; then
    exit 1
  fi
  exit 0
fi

log_info "Xcode: $(xcodebuild -version 2>/dev/null | tr '\n' ' ' || echo unknown)"
log_info "iOS Simulator SDK: $(xcrun --sdk iphonesimulator --show-sdk-path 2>/dev/null || echo missing)"
log_info "watchOS Simulator SDK: $(xcrun --sdk watchsimulator --show-sdk-path 2>/dev/null || echo missing)"

ensure_sim_device() {
  local label="$1"
  local runtime_regex="$2"
  local device_type_regex="$3"
  local existing_regex="$4"

  if xcrun simctl list devices available 2>/dev/null | grep -Eq "${existing_regex}"; then
    log_info "Available ${label} simulator already exists."
    return 0
  fi

  local runtime_id device_type_id
  runtime_id="$(xcrun simctl list runtimes available 2>/dev/null | grep -E "${runtime_regex}" | grep -oE 'com\.apple\.CoreSimulator\.SimRuntime\.[^ )]+' | tail -n 1 || true)"
  device_type_id="$(xcrun simctl list devicetypes 2>/dev/null | grep -E "${device_type_regex}" | grep -oE 'com\.apple\.CoreSimulator\.SimDeviceType\.[^ )]+' | tail -n 1 || true)"

  if [ -n "${runtime_id}" ] && [ -n "${device_type_id}" ]; then
    log_info "Creating simulator '${label}' (${device_type_id}, ${runtime_id})..."
    xcrun simctl create "${label}" "${device_type_id}" "${runtime_id}" >/dev/null
  else
    log_warn "No installed runtime/devicetype matched for ${label} (runtime=${runtime_id:-none})."
  fi
}

if ! xcrun simctl list runtimes available 2>/dev/null | grep -qi "watchOS"; then
  if [ "${INSTALL_WATCHOS}" = "1" ]; then
    log_info "Downloading watchOS Simulator runtime (timeout=${WATCHOS_TIMEOUT}s)..."
    python3 - "${WATCHOS_TIMEOUT}" <<'PY' || log_warn "watchOS Simulator runtime download did not complete within timeout."
import subprocess, sys
timeout = int(sys.argv[1])
proc = subprocess.run(["xcodebuild", "-downloadPlatform", "watchOS"], timeout=timeout)
sys.exit(proc.returncode)
PY
  else
    log_warn "watchOS Simulator runtime not installed. Re-run with EUV_APPLE_INSTALL_WATCHOS=1 to download via xcodebuild."
  fi
fi

ensure_sim_device "euv_ios_phone" "iOS" "iPhone (16|15|14)" "iPhone"
ensure_sim_device "euv_ipados_tablet" "iOS" "iPad" "iPad"
ensure_sim_device "euv_watchos_watch" "watchOS" "Apple Watch" "Apple Watch"

log_info "Installed Simulator runtimes:"
xcrun simctl list runtimes available || true
log_info "Available Apple Simulators:"
xcrun simctl list devices available | grep -E "iPhone|iPad|Apple Watch" | head -n 15 || true
