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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PROJECT="${PROJECT:-$ROOT_DIR/康康.xcodeproj}"
SCHEME="${SCHEME:-康康}"
APP_NAME="${APP_NAME:-$SCHEME}"
CONFIGURATION="${CONFIGURATION:-Debug}"
BUNDLE_ID="${BUNDLE_ID:-com.xuhuayong.kangkang}"
DERIVED_DATA_PATH="${DERIVED_DATA_PATH:-$ROOT_DIR/build/DerivedData}"
SIMULATOR_NAME="${SIMULATOR_NAME:-iPhone 16 Pro}"
SCREENSHOT_PATH="${SCREENSHOT_PATH:-$ROOT_DIR/build/screenshots/${SCHEME}-launch.png}"

require_tool() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "error: required tool not found: $1" >&2
    exit 1
  fi
}

require_full_xcode() {
  local developer_dir
  developer_dir="$(xcode-select -p 2>/dev/null || true)"
  if [[ "$developer_dir" != *"/Xcode.app/Contents/Developer"* ]]; then
    cat >&2 <<EOF
error: active developer directory is not a full Xcode install:
  ${developer_dir:-<unset>}

Select Xcode before running this script:
  sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
EOF
    exit 1
  fi
}

extract_udid() {
  sed -n 's/.*(\([0-9A-Fa-f-]\{36\}\)).*/\1/p' | head -n 1
}

find_simulator_udid() {
  if [[ -n "${SIMULATOR_UDID:-}" ]]; then
    echo "$SIMULATOR_UDID"
    return
  fi

  local udid
  udid="$(xcrun simctl list devices available | grep -F "$SIMULATOR_NAME" | extract_udid || true)"
  if [[ -n "$udid" ]]; then
    echo "$udid"
    return
  fi

  udid="$(
    xcrun simctl list devices available |
      awk '/-- iOS / { in_ios = 1; next } /-- / { in_ios = 0 } in_ios && /iPhone/ { print; exit }' |
      extract_udid || true
  )"
  if [[ -n "$udid" ]]; then
    echo "$udid"
    return
  fi

  echo "error: no available iOS simulator found. Install an iPhone simulator in Xcode." >&2
  exit 1
}

main() {
  require_tool xcode-select
  require_tool xcodebuild
  require_tool xcrun
  require_full_xcode

  local simulator_udid app_path
  simulator_udid="$(find_simulator_udid)"

  echo "Project: $PROJECT"
  echo "Scheme: $SCHEME"
  echo "Configuration: $CONFIGURATION"
  echo "Simulator: ${SIMULATOR_UDID:-$SIMULATOR_NAME} ($simulator_udid)"

  xcodebuild \
    -project "$PROJECT" \
    -scheme "$SCHEME" \
    -configuration "$CONFIGURATION" \
    -destination "id=$simulator_udid" \
    -derivedDataPath "$DERIVED_DATA_PATH" \
    build

  app_path="$DERIVED_DATA_PATH/Build/Products/${CONFIGURATION}-iphonesimulator/${APP_NAME}.app"
  if [[ ! -d "$app_path" ]]; then
    echo "error: built app not found at $app_path" >&2
    exit 1
  fi

  xcrun simctl boot "$simulator_udid" >/dev/null 2>&1 || true
  xcrun simctl bootstatus "$simulator_udid" -b
  if [[ "${OPEN_SIMULATOR:-1}" == "1" ]]; then
    open -a Simulator --args -CurrentDeviceUDID "$simulator_udid"
  fi

  xcrun simctl install "$simulator_udid" "$app_path"
  xcrun simctl launch "$simulator_udid" "$BUNDLE_ID"

  mkdir -p "$(dirname "$SCREENSHOT_PATH")"
  sleep "${SCREENSHOT_DELAY_SECONDS:-2}"
  xcrun simctl io "$simulator_udid" screenshot "$SCREENSHOT_PATH"

  echo "Launched $BUNDLE_ID"
  echo "Screenshot: $SCREENSHOT_PATH"
}

main "$@"
