#!/usr/bin/env bash
# Safari Web Extension build script — must run on macOS with Xcode installed.
# Produces an Xcode project under ./dist/Nithic Security/ that can be opened,
# signed, and submitted to the Mac App Store.
#
# Prerequisites (one-time):
#   - macOS 13+ with Xcode 15+ (App Store)
#   - Apple Developer Program membership ($99/yr)
#   - Run `xcode-select --install` and accept the license: `sudo xcodebuild -license`

set -euo pipefail

EXT_DIR="$(cd "$(dirname "$0")" && pwd)"
APP_NAME="Nithic Security"
BUNDLE_ID="ai.nithic.safari"
# The converter creates a folder named after --app-name inside --project-location.
DIST_DIR="$(dirname "$EXT_DIR")/dist"
PROJECT_DIR="$DIST_DIR/$APP_NAME"

if [[ "$(uname)" != "Darwin" ]]; then
  echo "❌ Safari build requires macOS. You're on: $(uname)"
  exit 1
fi
if ! command -v xcrun >/dev/null; then
  echo "❌ xcrun not found. Install Xcode from the App Store and run: xcode-select --install"
  exit 1
fi

echo "🍎 Converting Nithic extension → Safari Web Extension"
echo "   Source : $EXT_DIR"
echo "   Output : $PROJECT_DIR"
echo

# Wipe any prior conversion so signing settings stay fresh
rm -rf "$PROJECT_DIR"
mkdir -p "$DIST_DIR"

# Apple's converter consumes our MV3 source directly.
# --copy-resources : copy files instead of symlinking (safer when source moves)
# --force          : overwrite if existing (we already rm -rf'd above, but be explicit)
# --no-prompt      : non-interactive (uses sensible defaults)
# --no-open        : don't launch Xcode (we print next steps instead)
xcrun safari-web-extension-converter \
  "$EXT_DIR" \
  --project-location "$DIST_DIR" \
  --app-name "$APP_NAME" \
  --bundle-identifier "$BUNDLE_ID" \
  --swift \
  --copy-resources \
  --force \
  --no-prompt \
  --no-open

echo
echo "✅ Xcode project generated at:"
echo "   $PROJECT_DIR"
echo
echo "Next steps:"
echo "  1. Open the project: open \"$PROJECT_DIR\""
echo "  2. Set your Apple Developer Team under Signing & Capabilities"
echo "  3. Build & Run (⌘R) — Safari will prompt to enable the extension"
echo "  4. To distribute: Product → Archive → Distribute to App Store Connect"
echo
echo "For testing without signing:"
echo "  • Safari → Settings → Advanced → enable 'Show features for web developers'"
echo "  • Safari → Develop → Allow Unsigned Extensions (per-session)"
