#!/usr/bin/env bash
# Point the mobile app at MOBILE_CLIENT_PORT from .run/run.config.json / .run/.env.
source "$(dirname "${BASH_SOURCE[0]}")/common.sh"

# One record per app: each Metro listens on its own port, so a shared file would
# have two apps overwrite each other and force a rebuild on every switch.
mobile_native_port_file() {
  case "${MOBILE_SERVICE:-mobile-client}" in
    mobile-client) echo "${RUN_DIR}/mobile-native-port" ;;
    *)             echo "${RUN_DIR}/mobile-native-port-${MOBILE_SERVICE}" ;;
  esac
}

mobile_native_port_stale() {
  local file port="${MOBILE_CLIENT_PORT:-8081}"
  file="$(mobile_native_port_file)"
  [ ! -f "${file}" ] && return 0
  [ "$(cat "${file}")" != "${port}" ]
}

mobile_native_port_record() {
  mkdir -p "${RUN_DIR}"
  echo "${MOBILE_CLIENT_PORT:-8081}" > "$(mobile_native_port_file)"
}

mobile_native_port_invalidate() {
  rm -f "$(mobile_native_port_file)"
}

sync_mobile_app_port() {
  local app_dir port synced quiet="${1:-}" changed=""
  mobile_enabled || return 0
  app_dir="$(mobile_app_dir "${MOBILE_APP:-mobile-client}")"
  [ -n "${app_dir}" ] && [ -d "${app_dir}" ] || return 0
  port="${MOBILE_CLIENT_PORT:-8081}"
  changed="$("${RUN_PYTHON:-python3}" "${PACKAGE_DIR}/scripts/mobile-port.py" sync "${app_dir}" "${port}" 2>/dev/null || true)"
  [ -n "${changed}" ] || return 0

  mobile_native_port_invalidate
  if [ "${quiet}" = "quiet" ]; then
    echo "[run] mobile port changed — ${RUN_CMD:-run-stack} ios/android will point the app at the new bundler"
    return 0
  fi

  # Prefer if/continue over `&&` — a failed test in a while body trips set -e.
  while IFS= read -r synced || [ -n "${synced}" ]; do
    if [ -z "${synced}" ]; then
      continue
    fi
    echo "[run] mobile app: synced ${synced} → port ${port}"
  done <<< "${changed}"
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  require_docker
  ensure_env
  check_layout
  case "${1:-}" in
    quiet) sync_mobile_app_port quiet ;;
    *)     use_mobile_app "${1:-}" || exit 1; sync_mobile_app_port ;;
  esac
fi
