#!/usr/bin/env bash
# Generate native ios/android projects via expo prebuild (Expo apps only).
# Usage: run-stack prebuild [--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"

MOBILE_APP="${MOBILE_APP:-mobile-client}"

ensure_env
check_layout

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
echo "Done. Next: ${RUN_CMD:-run-stack} ios  or  ${RUN_CMD:-run-stack} android"
