#!/usr/bin/env bash
#
# Fetches ClicktermSDK.xcframework from a release artifact and places it at
# ios/ClicktermSDK.xcframework. Version-aware: it records the resolved
# download URL in ios/.clickterm-sdk-version and re-downloads whenever the
# framework on disk doesn't match the requested channel/version/URL, so
# updating the npm package always lands the matching binary. Identical
# repeat installs skip the download. Pass --force to always re-download.
#
# Configurable via environment variables:
#   CLICKTERM_IOS_SDK_CHANNEL   Release channel: dev | release (default: release)
#   CLICKTERM_IOS_SDK_VERSION   Version of the iOS SDK release (default: 1.2.0)
#   CLICKTERM_IOS_SDK_URL       Full download URL (overrides channel/version)
#   CLICKTERM_IOS_SDK_SHA256    Optional SHA-256 checksum to verify against
#
# The default URL points at the stable `release` channel on the Clickterm CDN:
#   https://cdn.clickterm.com/sdk/ios/release/<VERSION>/ClicktermSDK.xcframework.zip
#
# Internal devs who need an unreleased build can point CLICKTERM_IOS_SDK_URL
# at the rolling `dev` channel, e.g.:
#   https://cdn.clickterm.com/sdk/ios/dev/<VERSION>/ClicktermSDK.xcframework.zip
#   https://cdn.clickterm.com/sdk/ios/dev/latest/ClicktermSDK.xcframework.zip
#
# Usage:
#   scripts/fetch-xcframework.sh                    # download if missing or version changed
#   scripts/fetch-xcframework.sh --force            # always re-download
#   CLICKTERM_IOS_SDK_VERSION=1.2.0 scripts/fetch-xcframework.sh
#   CLICKTERM_IOS_SDK_CHANNEL=dev scripts/fetch-xcframework.sh

set -euo pipefail

# --- locate the repo root so the script works from any cwd -----------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
TARGET_DIR="${REPO_ROOT}/ios/ClicktermSDK.xcframework"
STAMP_FILE="${REPO_ROOT}/ios/.clickterm-sdk-version"

# --- configuration ---------------------------------------------------------
CHANNEL="${CLICKTERM_IOS_SDK_CHANNEL:-release}"
VERSION="${CLICKTERM_IOS_SDK_VERSION:-1.2.0}"
DEFAULT_URL="https://cdn.clickterm.com/sdk/ios/${CHANNEL}/${VERSION}/ClicktermSDK.xcframework.zip"
URL="${CLICKTERM_IOS_SDK_URL:-${DEFAULT_URL}}"
EXPECTED_SHA256="${CLICKTERM_IOS_SDK_SHA256:-}"

FORCE=0
if [[ "${1:-}" == "--force" ]]; then
  FORCE=1
fi

# --- skip only if the on-disk framework matches what we'd fetch ------------
# STAMP_FILE records the resolved URL of the framework currently installed.
# Re-download whenever it's missing or differs (a version/channel/URL bump),
# so updating the npm package always overwrites the binary; identical repeat
# installs stay download-free.
if [[ "${FORCE}" -eq 0 ]] \
  && [[ -f "${TARGET_DIR}/Info.plist" ]] \
  && [[ -f "${STAMP_FILE}" ]] \
  && [[ "$(cat "${STAMP_FILE}")" == "${URL}" ]]; then
  echo "✓ ClicktermSDK.xcframework already up to date (${URL}). Pass --force to re-download."
  exit 0
fi

# --- download to a temp dir -----------------------------------------------
TMP_DIR="$(mktemp -d -t clickterm-xcframework.XXXXXX)"
trap 'rm -rf "${TMP_DIR}"' EXIT

ZIP_PATH="${TMP_DIR}/ClicktermSDK.xcframework.zip"

echo "→ Downloading ${URL}"
if ! curl -fL --retry 3 --retry-delay 2 -o "${ZIP_PATH}" "${URL}"; then
  echo "✗ Failed to download from ${URL}" >&2
  exit 1
fi

# --- optional checksum verification ---------------------------------------
if [[ -n "${EXPECTED_SHA256}" ]]; then
  ACTUAL_SHA256="$(shasum -a 256 "${ZIP_PATH}" | awk '{print $1}')"
  if [[ "${ACTUAL_SHA256}" != "${EXPECTED_SHA256}" ]]; then
    echo "✗ SHA-256 mismatch" >&2
    echo "  expected: ${EXPECTED_SHA256}" >&2
    echo "  actual:   ${ACTUAL_SHA256}" >&2
    exit 1
  fi
  echo "✓ SHA-256 verified"
fi

# --- extract --------------------------------------------------------------
echo "→ Extracting to ${TARGET_DIR}"
rm -rf "${TARGET_DIR}"
mkdir -p "${REPO_ROOT}/ios"
unzip -q "${ZIP_PATH}" -d "${TMP_DIR}/extracted"

# Find the .xcframework inside the extracted tree (the zip may have a
# single top-level wrapper directory).
FRAMEWORK_SRC="$(find "${TMP_DIR}/extracted" -path '*/__MACOSX/*' -prune -o -type d -name '*.xcframework' -print | head -1)"
if [[ -z "${FRAMEWORK_SRC}" ]]; then
  echo "✗ No .xcframework found inside the downloaded archive" >&2
  exit 1
fi

mv "${FRAMEWORK_SRC}" "${TARGET_DIR}"

# --- sanity-check the structure -------------------------------------------
if [[ ! -f "${TARGET_DIR}/Info.plist" ]]; then
  echo "✗ ${TARGET_DIR}/Info.plist not found — archive looks malformed" >&2
  exit 1
fi

# --- record what we installed so the next run can version-check ------------
printf '%s\n' "${URL}" > "${STAMP_FILE}"

echo "✓ Installed ClicktermSDK.xcframework (${CHANNEL} ${VERSION})"
