#!/bin/bash
# BridgePort launcher: finds Python, sets things up the first time, opens the app.
HERE="$(cd "$(dirname "$0")/../Resources/app" && pwd)"
DATA="$HOME/BridgePort"
LOG="$DATA/bridgeport.log"
mkdir -p "$DATA"
exec >>"$LOG" 2>&1
echo "=== $(date) launch"

alert() {  # $1 = message
  osascript -e "display alert \"BridgePort\" message \"$1\" as critical" >/dev/null 2>&1
}
note() {
  osascript -e "display notification \"$1\" with title \"BridgePort\"" >/dev/null 2>&1
}

# 1. a Python that has the window toolkit
PY=""
for P in /opt/homebrew/bin/python3 /usr/local/bin/python3 \
         /Library/Frameworks/Python.framework/Versions/Current/bin/python3 \
         /usr/bin/python3; do
  if [ -x "$P" ] && "$P" -c "import tkinter" 2>/dev/null; then PY="$P"; break; fi
done
if [ -z "$PY" ]; then
  alert "BridgePort needs Python, which macOS can install for you. If a window asks to install developer tools, click Install, then open BridgePort again. Otherwise install Python from python.org."
  /usr/bin/xcode-select --install 2>/dev/null
  exit 1
fi
echo "python: $PY"

# 2. first-time setup: image library
"$PY" -c "import sys, tkinter; print('python', sys.version.split()[0], 'tk', tkinter.TkVersion)"
if ! "$PY" -c "import PIL" 2>/dev/null; then
  note "Setting up (one time only, about a minute)..."
  "$PY" -m pip install --user --quiet --disable-pip-version-check pillow \
    || "$PY" -m pip install --user --quiet --disable-pip-version-check --break-system-packages pillow
fi
if ! "$PY" -c "import PIL; print('pillow', PIL.__version__)"; then
  alert "First-time setup failed (couldn't install the image library). Check your internet connection and try again. Details: ~/BridgePort/bridgeport.log"
  exit 1
fi

# 3. pick the newest code: the app's own, or an installed update
CODE="$HERE"
if [ -f "$DATA/app/VERSION" ] && [ -f "$DATA/app/bridgeport_app.py" ]; then
  NEWER=$("$PY" -c "import sys
def v(p):
    try: return tuple(int(x) for x in open(p).read().strip().split('.'))
    except Exception: return (0,)
print('yes' if v(sys.argv[1]) > v(sys.argv[2]) else 'no')" "$DATA/app/VERSION" "$HERE/VERSION")
  [ "$NEWER" = "yes" ] && CODE="$DATA/app"
fi
echo "code: $CODE ($(cat "$CODE/VERSION" 2>/dev/null))"

# 4. first-time setup: fonts
mkdir -p "$HOME/Library/Fonts"
for F in "$HERE"/fonts/*.ttf "$CODE"/fonts/*.ttf; do
  [ -f "$F" ] || continue
  [ -f "$HOME/Library/Fonts/$(basename "$F")" ] || cp "$F" "$HOME/Library/Fonts/"
done

# 5. open the window
"$PY" "$CODE/bridgeport_app.py"
CODE=$?
if [ $CODE -ne 0 ]; then
  alert "BridgePort closed with an error. Details: ~/BridgePort/bridgeport.log"
fi
exit $CODE
