#!/bin/bash
# Bootstrap launcher — downloads libffmpeg.dylib on first run.
# This keeps the distributed .app free of LGPL code.

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
APP_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
FRAMEWORKS_DIR="$APP_DIR/Contents/Frameworks/Electron Framework.framework/Versions/A/Libraries"
FFMPEG_PATH="$FRAMEWORKS_DIR/libffmpeg.dylib"
REAL_BIN="$SCRIPT_DIR/$(basename "$0").real"

ELECTRON_VERSION="35.7.5"

if [ ! -f "$FFMPEG_PATH" ]; then
  ARCH=$(uname -m)
  if [ "$ARCH" = "arm64" ]; then
    PLATFORM="darwin-arm64"
  else
    PLATFORM="darwin-x64"
  fi

  ELECTRON_URL="https://github.com/electron/electron/releases/download/v${ELECTRON_VERSION}/electron-v${ELECTRON_VERSION}-${PLATFORM}.zip"
  TMP_DIR=$(mktemp -d)
  ZIP_PATH="$TMP_DIR/electron.zip"

  osascript -e 'display dialog "QAIRT Visualizer requires media components that must be downloaded on first launch.\n\nClick OK to begin - the app will open automatically when the download is complete." with title "QAIRT Visualizer" buttons {"OK"} default button "OK"' 2>/dev/null

  if ! command -v curl &>/dev/null; then
    osascript -e 'display alert "QAIRT Visualizer" message "Cannot download required components: curl not found." as critical' 2>/dev/null
    exit 1
  fi

  curl -fsSL -o "$ZIP_PATH" "$ELECTRON_URL" 2>/dev/null || curl -fsSLk -o "$ZIP_PATH" "$ELECTRON_URL" 2>/dev/null
  curl_exit=$?

  if [ $curl_exit -ne 0 ]; then
    rm -rf "$TMP_DIR"
    osascript -e 'display alert "QAIRT Visualizer" message "Failed to download required components. Please check your internet connection and try again." as critical' 2>/dev/null
    exit 1
  fi

  MEMBER="Electron.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Libraries/libffmpeg.dylib"
  mkdir -p "$FRAMEWORKS_DIR"
  unzip -o -j "$ZIP_PATH" "$MEMBER" -d "$FRAMEWORKS_DIR" >/dev/null 2>&1

  rm -rf "$TMP_DIR"

  if [ ! -f "$FFMPEG_PATH" ]; then
    osascript -e 'display alert "QAIRT Visualizer" message "Failed to extract required components. Please try again." as critical' 2>/dev/null
    exit 1
  fi
fi

exec "$REAL_BIN" "$@"
