#!/bin/zsh
set -euo pipefail

PACKAGE_DIR="${0:A:h}"
EXTENSION_SOURCE="$PACKAGE_DIR/CEP Extension/Nexus AE Voice Assistant Beta"
EXTENSION_TARGET="$HOME/Library/Application Support/Adobe/CEP/extensions/Nexus AE Voice Assistant Beta"
LAUNCHER="$HOME/Applications/Nexa.command"
LEGACY_LAUNCHER="$HOME/Applications/Nexus AE Voice Assistant Beta.command"

if [ ! -d "$EXTENSION_SOURCE" ]; then
  echo "Could not find the bundled CEP extension."
  exit 1
fi

echo "Installing Nexa AE Voice Assistant Beta..."
mkdir -p "$(dirname "$EXTENSION_TARGET")"
rm -rf "$EXTENSION_TARGET"
/usr/bin/rsync -a "$EXTENSION_SOURCE/" "$EXTENSION_TARGET/"

chmod +x "$EXTENSION_TARGET/electron-overlay/start_nexus_voice_overlay.command" 2>/dev/null || true
chmod +x "$EXTENSION_TARGET/electron-overlay/start_nexus_voice_overlay_background.command" 2>/dev/null || true
chmod +x "$EXTENSION_TARGET/electron-overlay/stop_nexus_voice_overlay.command" 2>/dev/null || true

for version in 9 10 11 12 13 14; do
  /usr/bin/defaults write "com.adobe.CSXS.$version" PlayerDebugMode 1 >/dev/null 2>&1 || true
done

/usr/bin/xattr -dr com.apple.quarantine "$EXTENSION_TARGET" >/dev/null 2>&1 || true

mkdir -p "$HOME/Applications"
rm -f "$LEGACY_LAUNCHER"
cat > "$LAUNCHER" <<'LAUNCHER'
#!/bin/zsh
set -euo pipefail

OVERLAY="$HOME/Library/Application Support/Adobe/CEP/extensions/Nexus AE Voice Assistant Beta/electron-overlay/start_nexus_voice_overlay.command"
if [ ! -x "$OVERLAY" ]; then
  echo "Nexa AE Voice Assistant Beta is not installed yet."
  exit 1
fi

exec "$OVERLAY"
LAUNCHER
chmod +x "$LAUNCHER"
/usr/bin/xattr -d com.apple.quarantine "$LAUNCHER" >/dev/null 2>&1 || true

echo ""
echo "Installed."
echo "1. Open After Effects."
echo "2. Go to Window > Extensions > Nexa."
echo "3. Launch Nexa from: $LAUNCHER"
echo ""
echo "Starting Nexa now..."
/usr/bin/open "$LAUNCHER" >/dev/null 2>&1 || true
