#!/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"

mobile_native_port_file() {
  echo "${RUN_DIR}/mobile-native-port"
}

mobile_native_port_stale() {
  local file="${RUN_DIR}/mobile-native-port" port="${MOBILE_CLIENT_PORT:-8081}"
  [ ! -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="$(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
  sync_mobile_app_port "$@"
fi
