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

SCHEME="App"
PROJECT="ios/App/App.xcodeproj"
WORKSPACE="ios/App/App.xcworkspace"
ARCHIVE_PATH="build/App.xcarchive"
IPA_DIR="build"
EXPORT_OPTIONS="${EXPORT_OPTIONS:-scripts/export-options.plist}"

echo "=== FarmaFinder iOS Build Script ==="

echo "[1/6] Installing frontend dependencies..."
(cd frontend && npm ci)

echo "[2/6] Building web bundle..."
npm run build:web

echo "[3/6] Syncing Capacitor..."
if [ ! -d "ios/App/App.xcodeproj" ]; then
  echo "  Adding iOS platform..."
  npx cap add ios
fi
npx cap sync ios

echo "[4/6] Installing CocoaPods..."
(cd ios/App && pod install --repo-update)

echo "[5/6] Archiving..."
xcodebuild archive \
  -workspace "$WORKSPACE" \
  -scheme "$SCHEME" \
  -configuration Release \
  -destination "generic/platform=iOS" \
  -archivePath "$ARCHIVE_PATH" \
  -allowProvisioningUpdates \
  | xcpretty --color || true

echo "[6/6] Exporting IPA..."
xcodebuild -exportArchive \
  -archivePath "$ARCHIVE_PATH" \
  -exportOptionsPlist "$EXPORT_OPTIONS" \
  -exportPath "$IPA_DIR" \
  -allowProvisioningUpdates \
  | xcpretty --color || true

IPA_FILE=$(find "$IPA_DIR" -name "*.ipa" -maxdepth 1 | head -1)
if [ -n "$IPA_FILE" ]; then
  echo ""
  echo "=== Build complete ==="
  echo "IPA: $IPA_FILE"
  echo "Size: $(du -h "$IPA_FILE" | cut -f1)"
else
  echo "ERROR: IPA not found in $IPA_DIR/"
  exit 1
fi
