#!/usr/bin/env bash
# Build and upload iOS IPA to App Store Connect.
# Prefer: kasy ios release (configure first with kasy ios configure)

set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

APPLE_ENV="${ROOT}/.kasy/apple.env"
UPLOAD=1
BUMP=1
VERSION_NAME=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --no-upload) UPLOAD=0; shift ;;
    --no-bump) BUMP=0; shift ;;
    --version-name)
      VERSION_NAME="${2:-}"
      shift 2
      ;;
    *) echo "Unknown option: $1" >&2; exit 1 ;;
  esac
done

if [[ ! -f pubspec.yaml ]]; then
  echo "pubspec.yaml not found. Run from the Flutter project root." >&2
  exit 1
fi

check_google_ios_url_scheme() {
  local google_plist="${ROOT}/ios/Runner/GoogleService-Info.plist"
  local info_plist="${ROOT}/ios/Runner/Info.plist"

  [[ -f "$google_plist" ]] || return 0

  if [[ ! -f "$info_plist" ]]; then
    echo "ios/Runner/Info.plist not found." >&2
    exit 1
  fi

  local reversed_client_id
  reversed_client_id="$(/usr/libexec/PlistBuddy -c "Print :REVERSED_CLIENT_ID" "$google_plist" 2>/dev/null || true)"
  if [[ -z "$reversed_client_id" ]]; then
    echo "REVERSED_CLIENT_ID not found in ios/Runner/GoogleService-Info.plist." >&2
    echo "Run flutterfire configure before building iOS." >&2
    exit 1
  fi

  if ! /usr/libexec/PlistBuddy -c "Print :CFBundleURLTypes" "$info_plist" 2>/dev/null | grep -Fq "$reversed_client_id"; then
    echo "Google Sign-In iOS URL scheme mismatch." >&2
    echo "Expected CFBundleURLSchemes to include: $reversed_client_id" >&2
    echo "Run: kasy ios clean, then rebuild. If it still fails, re-run flutterfire configure/project setup." >&2
    exit 1
  fi
}

check_google_ios_url_scheme

if [[ "$BUMP" -eq 1 ]]; then
  BUMP_SCRIPT="${ROOT}/scripts/bump-ios-version.js"
  if [[ -f "$BUMP_SCRIPT" ]]; then
    if [[ -n "$VERSION_NAME" ]]; then
      node "$BUMP_SCRIPT" --version-name "$VERSION_NAME"
    else
      node "$BUMP_SCRIPT"
    fi
  else
    echo "bump-ios-version.js not found" >&2
    exit 1
  fi
fi

load_dart_defines() {
  DEFINES_ARGS=()
  if [[ -f .dart_defines ]]; then
    while IFS= read -r line || [[ -n "$line" ]]; do
      [[ -z "$line" || "$line" =~ ^# ]] && continue
      DEFINES_ARGS+=("$line")
    done < .dart_defines
  fi
  # Projects generated by Kasy may inline DEFINES in the Makefile instead of .dart_defines
  if [[ ${#DEFINES_ARGS[@]} -eq 0 && -f Makefile ]]; then
    local block
    block="$(awk '/^DEFINES :=/{flag=1;next} flag && /^[^[:space:]#]/{exit} flag{print}' Makefile)"
    while IFS= read -r line || [[ -n "$block" ]]; do
      line="${line%%\\}" # trim trailing backslash from Makefile continuation
      line="$(echo "$line" | xargs)"
      [[ -z "$line" || "$line" =~ ^# ]] && continue
      DEFINES_ARGS+=("$line")
    done <<< "$block"
  fi
}

load_dart_defines

# Use the FVM-pinned Flutter SDK when this project has one (see .fvmrc) —
# a bare `flutter` here would silently build with whatever's global instead.
FLUTTER="flutter"
[[ -d .fvm/flutter_sdk ]] && FLUTTER="fvm flutter"

# Swift Package Manager (default since Flutter 3.24+) resolves facebook_app_events
# via the facebook-ios-sdk SPM package, while flutter_facebook_auth (no SPM support)
# still pulls the same SDK through CocoaPods -- both embed FBSDKCoreKit/FBAEMKit,
# and Xcode fails the archive with "Multiple commands produce ...framework". Forcing
# CocoaPods-only resolution (how this worked before Flutter 3.47) avoids the double
# link. Revisit once flutter_facebook_auth ships SPM support upstream.
export FLUTTER_SWIFT_PACKAGE_MANAGER=false

echo "Building IPA..."
if [[ ${#DEFINES_ARGS[@]} -gt 0 ]]; then
  $FLUTTER build ipa --release "${DEFINES_ARGS[@]}"
else
  $FLUTTER build ipa --release
fi

if [[ "$UPLOAD" -eq 0 ]]; then
  echo "IPA built at build/ios/ipa/"
  exit 0
fi

if [[ ! -f "$APPLE_ENV" ]]; then
  echo "Missing $APPLE_ENV — run: kasy ios configure" >&2
  exit 1
fi

# shellcheck disable=SC1090
source "$APPLE_ENV"

if [[ -z "${APP_STORE_API_KEY:-}" || -z "${APP_STORE_ISSUER_ID:-}" ]]; then
  echo "APP_STORE_API_KEY and APP_STORE_ISSUER_ID required in .kasy/apple.env" >&2
  exit 1
fi

shopt -s nullglob
IPA=(build/ios/ipa/*.ipa)
shopt -u nullglob

if [[ ${#IPA[@]} -eq 0 || ! -f "${IPA[0]}" ]]; then
  echo "IPA not found in build/ios/ipa/" >&2
  exit 1
fi

echo "Uploading to App Store Connect..."
xcrun altool --upload-app --type ios -f "${IPA[0]}" \
  --apiKey "$APP_STORE_API_KEY" \
  --apiIssuer "$APP_STORE_ISSUER_ID"

echo "Upload complete."
