#!/usr/bin/env bash
# Generate native ios/android projects via expo prebuild (Expo apps only).
# Usage: run-stack prebuild [app] [--clean] [expo prebuild args...]
set -euo pipefail

# shellcheck source=common.sh
source "$(dirname "${BASH_SOURCE[0]}")/common.sh"
# shellcheck source=sync-mobile-port.sh
source "$(dirname "${BASH_SOURCE[0]}")/sync-mobile-port.sh"

# A leading bare word is the app; everything else forwards to expo untouched.
target=""
case "${1:-}" in
  ""|-*) ;;
  *) target="$1"; shift ;;
esac

ensure_env
check_layout
use_mobile_app "${target}" || exit 1

if ! mobile_enabled; then
  echo "Mobile is disabled (RUN_MOBILE=false). Enable it in run.config.json." >&2
  exit 1
fi

case "$(mobile_stack_kind "${MOBILE_APP}")" in
  expo) ;;
  *)
    echo "prebuild is only for Expo apps (detected $(mobile_stack_kind "${MOBILE_APP}"))." >&2
    exit 1
    ;;
esac

if [ ! -d "${FRONTEND_DIR}/node_modules" ]; then
  echo "Host pnpm deps missing. In ${FRONTEND_DIR} run: pnpm --filter ${MOBILE_APP}... install" >&2
  exit 1
fi

echo "Running expo prebuild for ${MOBILE_APP}..."
mobile_run_in_frontend "${MOBILE_APP}" expo prebuild "$@"

# Native dirs were regenerated — re-apply Metro port and force a rebuild next ios/android.
sync_mobile_app_port
mobile_native_port_invalidate
suffix=""
[ "${MOBILE_SERVICE:-mobile-client}" = mobile-client ] || suffix=" ${MOBILE_APP}"
echo "Done. Next: ${RUN_CMD:-run-stack} ios${suffix}  or  ${RUN_CMD:-run-stack} android${suffix}"
