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

usage() {
  cat <<'EOF'
Usage:
  scripts/ios-write-version-xcconfig.sh [--build-number 7]

Writes apps/ios/build/Version.xcconfig from root package.json.version:
- OPENCLAW_GATEWAY_VERSION = exact package.json version
- OPENCLAW_MARKETING_VERSION = short iOS/App Store version
- OPENCLAW_BUILD_VERSION = explicit build number or local numeric fallback
EOF
}

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
IOS_DIR="${ROOT_DIR}/apps/ios"
BUILD_DIR="${IOS_DIR}/build"
VERSION_XCCONFIG="${IOS_DIR}/build/Version.xcconfig"
PACKAGE_VERSION="$(cd "${ROOT_DIR}" && node -p "require('./package.json').version" 2>/dev/null || true)"
BUILD_NUMBER=""

prepare_build_dir() {
  if [[ -L "${BUILD_DIR}" ]]; then
    echo "Refusing to use symlinked build directory: ${BUILD_DIR}" >&2
    exit 1
  fi

  mkdir -p "${BUILD_DIR}"
}

write_generated_file() {
  local output_path="$1"
  local tmp_file=""

  if [[ -e "${output_path}" && -L "${output_path}" ]]; then
    echo "Refusing to overwrite symlinked file: ${output_path}" >&2
    exit 1
  fi

  tmp_file="$(mktemp "${output_path}.XXXXXX")"
  cat >"${tmp_file}"
  mv -f "${tmp_file}" "${output_path}"
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --)
      shift
      ;;
    --build-number)
      BUILD_NUMBER="${2:-}"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage
      exit 1
      ;;
  esac
done

PACKAGE_VERSION="$(printf '%s' "${PACKAGE_VERSION}" | tr -d '\n' | xargs)"
if [[ -z "${PACKAGE_VERSION}" ]]; then
  echo "Unable to read package.json.version from ${ROOT_DIR}/package.json." >&2
  exit 1
fi

if [[ "${PACKAGE_VERSION}" =~ ^([0-9]{4}\.[0-9]{1,2}\.[0-9]{1,2})([.-]?beta[.-][0-9]+)?$ ]]; then
  MARKETING_VERSION="${BASH_REMATCH[1]}"
else
  echo "Unsupported package.json.version '${PACKAGE_VERSION}'. Expected 2026.3.12 or 2026.3.12-beta.1." >&2
  exit 1
fi

if [[ -z "${BUILD_NUMBER}" ]]; then
  BUILD_NUMBER="$(cd "${ROOT_DIR}" && git rev-list --count HEAD 2>/dev/null || printf '0')"
fi

if [[ ! "${BUILD_NUMBER}" =~ ^[0-9]+$ ]]; then
  echo "Invalid build number '${BUILD_NUMBER}'. Expected digits only." >&2
  exit 1
fi

prepare_build_dir

write_generated_file "${VERSION_XCCONFIG}" <<EOF
// Auto-generated by scripts/ios-write-version-xcconfig.sh.
// Local version override; do not commit.
OPENCLAW_GATEWAY_VERSION = ${PACKAGE_VERSION}
OPENCLAW_MARKETING_VERSION = ${MARKETING_VERSION}
OPENCLAW_BUILD_VERSION = ${BUILD_NUMBER}
EOF

echo "Prepared iOS version settings: gateway=${PACKAGE_VERSION} marketing=${MARKETING_VERSION} build=${BUILD_NUMBER}"
