#!/bin/bash
# Overcoat.app: prepare Overcoat's environment on first open, then open Overcoat.
RES="$(cd "$(dirname "$0")/../Resources" && pwd)"
SUPPORT="$HOME/Library/Application Support/Warden"
export UV_PROJECT_ENVIRONMENT="$SUPPORT/venv" UV_PYTHON_INSTALL_DIR="$SUPPORT/python" UV_CACHE_DIR="$SUPPORT/cache"
export UV_PYTHON_PREFERENCE=only-managed
export WARDEN_HOME="${WARDEN_HOME:-$HOME/assistant}" WARDEN_SUPPORT="$SUPPORT" WARDEN_WEB_DIST="$RES/app/web/dist"
export WARDEN_GOOGLE_SOURCE="${WARDEN_GOOGLE_SOURCE:-google}"
export PATH="$SUPPORT/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin:/usr/local/bin"
mkdir -p "$SUPPORT/logs"
LOG="$SUPPORT/logs/app.log"
VERSION="$(cat "$RES/app/VERSION")"

note()  { /usr/bin/osascript -e "display notification \"$1\" with title \"Overcoat\"" >/dev/null 2>&1; }
alert() { /usr/bin/osascript -e "display alert \"Overcoat\" message \"$1\" as critical" >/dev/null 2>&1; }

if [[ ! -x "$SUPPORT/venv/bin/warden" || "$(cat "$SUPPORT/venv/.warden-version" 2>/dev/null)" != "$VERSION" ]]; then
  note "Getting Overcoat ready. The first time takes a minute or two."
  echo "== $(date) installing $VERSION" >>"$LOG"
  if ! "$RES/uv" sync --frozen --no-dev --no-editable --python 3.12 --project "$RES/app" >>"$LOG" 2>&1; then
    alert "Overcoat couldn't finish getting ready. Check your internet connection and open it again. (Details: $LOG)"
    exit 1
  fi
  echo "$VERSION" >"$SUPPORT/venv/.warden-version"
fi

if [[ "$1" == "--serve" ]]; then exec "$SUPPORT/venv/bin/warden" serve; fi
if ! "$SUPPORT/venv/bin/warden" setup >>"$LOG" 2>&1; then
  alert "Overcoat didn't start. Details are in $WARDEN_HOME/logs/warden.log"
  exit 1
fi
