#!/bin/bash
set -e
RES="$(cd "$(dirname "$0")/../Resources" && pwd)"; DATA="$HOME/Library/Application Support/Nucleus"; VENV="$DATA/venv"; LOG="$DATA/nucleus.log"; mkdir -p "$DATA"
PY=""; for c in /opt/homebrew/bin/python3 /usr/local/bin/python3 /usr/bin/python3 "$(which python3 2>/dev/null)"; do [ -x "$c" ] && "$c" -c "import sys; assert sys.version_info>=(3,10)" 2>/dev/null && PY="$c" && break; done
if [ -z "$PY" ]; then ARCH=$(uname -m); [ "$ARCH" = "arm64" ] && T="aarch64-apple-darwin" || T="x86_64-apple-darwin"; osascript -e 'display notification "Downloading Nucleus Python runtime (first launch only)..." with title "Nucleus"'; curl -sL "https://github.com{T}-install_only_stripped.tar.gz" | tar -xz -C "$DATA"; PY="$DATA/python/bin/python3"; fi
[ ! -x "$VENV/bin/python" ] && osascript -e 'display notification "Setting up Nucleus local engine on this Mac..." with title "Nucleus"' && "$PY" -m venv "$VENV" >>"$LOG" 2>&1 && "$VENV/bin/pip" install --quiet --upgrade pip fastapi uvicorn requests pypdf >>"$LOG" 2>&1
export NUCLEUS_PREVIEW_DATA="$DATA/data" NUCLEUS_PREVIEW_HOST="127.0.0.1" NUCLEUS_PREVIEW_PORT="18002" NUCLEUS_DESKTOP_MODE="1" PYTHONDONTWRITEBYTECODE="1"
U="http://127.0.0.1:18002"
if ! curl -s "$U/" >/dev/null 2>&1; then
  cd "$RES/app" && nohup "$VENV/bin/python" server.py >>"$LOG" 2>&1 &
  for i in $(seq 1 40); do curl -s "$U/" >/dev/null 2>&1 && break; sleep 0.25; done
fi
if [ -d "/Applications/Google Chrome.app" ]; then open -na "Google Chrome" --args --app="$U"
elif [ -d "/Applications/Microsoft Edge.app" ]; then open -na "Microsoft Edge" --args --app="$U"
elif [ -d "/Applications/Brave Browser.app" ]; then open -na "Brave Browser" --args --app="$U"
else open "$U"; fi
