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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
VERSION_FILE="$ROOT_DIR/version.json"
PROJECT_FILE="$ROOT_DIR/iKeyMon.xcodeproj/project.pbxproj"

if [[ ! -f "$VERSION_FILE" ]]; then
  echo "❌ version.json not found at $VERSION_FILE" >&2
  exit 1
fi

if ! command -v jq >/dev/null 2>&1; then
  echo "❌ jq is required but not found in PATH" >&2
  exit 1
fi

MARKETING_VERSION="$(jq -r '.marketing_version // empty' "$VERSION_FILE")"
if [[ -z "$MARKETING_VERSION" ]]; then
  echo "❌ marketing_version missing in $VERSION_FILE" >&2
  exit 1
fi

if [[ ! "$MARKETING_VERSION" =~ ^[0-9]{2}\.[0-9]+\.[0-9]+$ ]]; then
  echo "❌ marketing_version '$MARKETING_VERSION' must follow YY.major.minor (e.g. 26.1.2)" >&2
  exit 1
fi

BUILD_NUMBER="${BUILD_NUMBER:-$(git -C "$ROOT_DIR" rev-list --count HEAD)}"
if [[ -z "$BUILD_NUMBER" ]]; then
  echo "❌ Unable to derive BUILD_NUMBER" >&2
  exit 1
fi

update_setting() {
  local key="$1"
  local value="$2"
  local tmp
  tmp="$(mktemp)"
  LC_ALL=C sed -E "s/(${key}[[:space:]]*=[[:space:]]*)[^;]+;/\\1${value};/g" "$PROJECT_FILE" >"$tmp"
  if cmp -s "$tmp" "$PROJECT_FILE"; then
    if ! grep -q "${key} = ${value};" "$PROJECT_FILE"; then
      rm -f "$tmp"
      echo "❌ Failed to update ${key} in $PROJECT_FILE" >&2
      exit 1
    fi
    rm -f "$tmp"
    return
  fi
  mv "$tmp" "$PROJECT_FILE"
}

update_setting "MARKETING_VERSION" "$MARKETING_VERSION"
update_setting "CURRENT_PROJECT_VERSION" "$BUILD_NUMBER"

echo "✅ Synced marketing version $MARKETING_VERSION and build $BUILD_NUMBER into Xcode project."
