#!/bin/bash
set -u

CONTENTS="$(cd "$(dirname "$0")/.." && pwd)"
RESOURCES="$CONTENTS/Resources"
SUPPORT="$HOME/Library/Application Support/Intersignal/Braid"
RUNTIME="$SUPPORT/runtime"
LOGDIR="$SUPPORT/logs"
LOG="$LOGDIR/Braid-launch.log"
mkdir -p "$RUNTIME" "$LOGDIR" "$SUPPORT/inbox"
chmod 700 "$SUPPORT" "$RUNTIME" "$LOGDIR" "$SUPPORT/inbox" 2>/dev/null || true
exec >>"$LOG" 2>&1

echo "--- Braid 1.5.2 launch $(date -u +%Y-%m-%dT%H:%M:%SZ) ---"

fail_dialog() {
  local msg="$1"
  /usr/bin/osascript - "$msg" <<'APPLESCRIPT' >/dev/null 2>&1 || true
on run argv
  set detail to item 1 of argv
  display dialog "Braid could not start." & return & return & detail & return & return & "Log: ~/Library/Application Support/Intersignal/Braid/logs/Braid-launch.log" buttons {"OK"} default button "OK" with icon caution
end run
APPLESCRIPT
  exit 1
}

python_works() {
  "$1" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3,10) else 1)' >/dev/null 2>&1
}

find_python() {
  local candidates=(
    "$RUNTIME/venv/bin/python3"
    "/opt/homebrew/bin/python3"
    "/usr/local/bin/python3"
    "$HOME/.pyenv/shims/python3"
    "/Library/Frameworks/Python.framework/Versions/Current/bin/python3"
    "/usr/bin/python3"
  )
  local p
  for p in "${candidates[@]}"; do
    if [[ -x "$p" ]] && python_works "$p"; then
      echo "$p"
      return 0
    fi
  done
  if command -v python3 >/dev/null 2>&1; then
    p="$(command -v python3)"
    if python_works "$p"; then
      echo "$p"
      return 0
    fi
  fi
  return 1
}

WHEEL=""
for candidate in "$RESOURCES"/braid_client-1.5.2-*.whl; do
  if [[ -f "$candidate" ]]; then WHEEL="$candidate"; break; fi
done
[[ -n "$WHEEL" ]] || fail_dialog "The bundled Braid wheel is missing. Re-download the release."

BASE_PY="$(find_python 2>/dev/null)" || fail_dialog "Python 3.10 or newer was not found. Use the standalone Braid DMG when available, or install Python 3 and reopen Braid."

VENV="$RUNTIME/venv"
if [[ ! -x "$VENV/bin/python3" ]]; then
  rm -rf "$VENV"
  "$BASE_PY" -m venv "$VENV" || fail_dialog "Could not create the private Braid runtime."
fi
PY="$VENV/bin/python3"
INSTALLED="$($PY -c 'import braid_client; print(braid_client.__version__)' 2>/dev/null || true)"
if [[ "$INSTALLED" != "1.5.2" ]]; then
  "$PY" -m pip install --disable-pip-version-check --no-input --upgrade "$WHEEL" || fail_dialog "Braid dependencies could not be installed. The standalone DMG avoids this bootstrap step."
fi

export BRAID_RECEIVER_DIR="$SUPPORT/inbox"
export BRAID_CLI_COMMAND="$CONTENTS/MacOS/braid-client"
cd "$SUPPORT" || exit 1
exec "$VENV/bin/braid-client" demo
