#!/bin/bash
# ProofJack.app launcher. Generated by make_app.py.
APP="$(cd "$(dirname "$0")/../.." && pwd)"
SRC="$APP/Contents/Resources/proofjack"
VERSION="0.1.25"
BUILD="3e3e21823973"   # fingerprint of the code: a rebuild with the same version still restarts the service
URL="http://127.0.0.1:8717/live"
STATE="$HOME/.proofjack"
VENV="$STATE/venv"
VPY="$VENV/bin/python"
mkdir -p "$STATE"
exec >>"$STATE/app.log" 2>&1
T0=$(/bin/date +%s)
log() { echo "[$(/bin/date +%T) +$(( $(/bin/date +%s) - T0 ))s] $1"; }
echo "=== $(date) launch $VERSION from $APP"
export PATH="/opt/homebrew/bin:/usr/local/bin:/Library/Frameworks/Python.framework/Versions/Current/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"
export PROOFJACK_PY="$VPY"
HIDDEN=""; [ "${1:-}" = "--menubar" ] && HIDDEN="--hidden"   # started at login: menu bar only, no window
# A release carries ProofJack compiled into one program (no Python needed); a development build, source.
CORE="$APP/Contents/Resources/core/ProofJack"   # named ProofJack so it shows as ProofJack in Activity Monitor
# Once you have opened the app, clear the download flag from its own files so macOS does not stop the
# compiled program inside it separately.
/usr/bin/xattr -dr com.apple.quarantine "$APP" 2>/dev/null || true
if [ -x "$CORE" ]; then COMPILED=1; HOOKMARK="$CORE"; else COMPILED=0; HOOKMARK="$SRC/hooks/proofjack_hook.py"; fi
pjrun() {   # pjrun install-hooks | service ACTION
  if [ $COMPILED = 1 ]; then "$CORE" "$@"
  else case "$1" in
    install-hooks) shift; "$VPY" "$SRC/hooks/install_claude_code.py" "$@" ;;
    service) shift; "$VPY" "$SRC/service.py" "$@" ;;
  esac; fi
}

notify() { /usr/bin/osascript -e "display notification \"$1\" with title \"ProofJack\"" >/dev/null 2>&1; }
fail()   { echo "FAIL: $1"; /usr/bin/osascript -e "display alert \"ProofJack\" message \"$1\" as critical" >/dev/null 2>&1; exit 1; }
up()     { /usr/bin/curl -fsS --max-time 2 "http://127.0.0.1:8717/health" >/dev/null 2>&1; }

# Editors that take the ProofJack extension: name|CLI|extensions folder
EDITORS="VS Code|/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code|$HOME/.vscode/extensions
Cursor|/Applications/Cursor.app/Contents/Resources/app/bin/cursor|$HOME/.cursor/extensions"
editor_missing_ext() {   # true if an installed editor lacks this version of the extension
  echo "$EDITORS" | while IFS='|' read -r name cli dir; do
    [ -x "$cli" ] && [ ! -d "$dir/proofjack.proofjack-sensor-0.1.4" ] && { echo "$name"; break; }
  done | /usr/bin/grep -q .
}

install_extensions() {
  echo "$EDITORS" | while IFS='|' read -r name cli dir; do
    if [ -x "$cli" ] && [ ! -d "$dir/proofjack.proofjack-sensor-0.1.4" ]; then
      log "installing extension into $name"
      "$cli" --install-extension "$APP/Contents/Resources/proofjack-sensor.vsix" --force >/dev/null 2>&1 \
        && { log "extension installed into $name"; notify "Connected to $name. Reload its window to start recording your edits."; }
    fi
  done
}
open_panel() {
  # The app process becomes the panel window (exec), so macOS keeps it alive, and opening
  # ProofJack again while it is open brings the window forward instead of starting another.
  log "opening panel"
  /usr/bin/pkill -f "proofjack/panel.js" 2>/dev/null   # only ever one ProofJack menu bar app
  # macOS names a process after its program file, so the panel (and its WebKit helpers) would show as
  # "osascript". Run an unmodified copy of /usr/bin/osascript named ProofJack instead; Apple's signature
  # stays intact. Re-copied after a macOS update changes osascript; falls back to the original if the
  # copy will not run.
  PANEL="$HOME/.proofjack/bin/ProofJack"
  if ! /usr/bin/cmp -s /usr/bin/osascript "$PANEL"; then
    /bin/mkdir -p "$HOME/.proofjack/bin" && /bin/cp -f /usr/bin/osascript "$PANEL" 2>/dev/null || PANEL=/usr/bin/osascript
  fi
  "$PANEL" -e 'return' >/dev/null 2>&1 || { log "named panel copy will not run; using /usr/bin/osascript"; PANEL=/usr/bin/osascript; }
  exec "$PANEL" -l JavaScript "$SRC/panel.js" "$URL" "$APP/Contents/Resources" $HIDDEN
}

# Fast path: already set up and running -> open the panel immediately. Log why it is skipped.
FP_WHY=""
[ "$(cat "$STATE/installed" 2>/dev/null)" = "$VERSION $BUILD $SRC" ] || FP_WHY="new or moved version"
hooks_ok() { /usr/bin/grep -qF "$HOOKMARK" "$HOME/.claude/settings.json" 2>/dev/null && /usr/bin/grep -qF '"SubagentStart"' "$HOME/.claude/settings.json" 2>/dev/null; }   # present and current (subagent events)
hooks_ok || FP_WHY="$FP_WHY; hooks missing or out of date"
up || FP_WHY="$FP_WHY; service not answering"
[ -n "$FP_WHY" ] && log "full start: ${FP_WHY#; }"
if [ "$(cat "$STATE/installed" 2>/dev/null)" = "$VERSION $BUILD $SRC" ] \
   && hooks_ok \
   && up; then
  if [ -f "$APP/Contents/Resources/proofjack-sensor.vsix" ] && editor_missing_ext; then
    install_extensions &          # an editor was installed after ProofJack
  fi
  open_panel
  log "fast path: opened panel"
  exit 0
fi

# 1. Must run from a permanent location.
#    macOS runs a just-downloaded app from a random read-only copy (App Translocation) until it is
#    moved with Finder. If the real copy is already in Applications, clear the download flag on it
#    (the person has just approved it with Open Anyway) and open that one instead.
case "$APP" in
  (*/AppTranslocation/*)
    for real in "/Applications/ProofJack.app" "$HOME/Applications/ProofJack.app"; do
      if [ -d "$real" ]; then
        /usr/bin/xattr -dr com.apple.quarantine "$real" 2>/dev/null
        # Only hand over once the flag is really gone, or macOS would translocate it again (a loop).
        # Open it after this copy has quit: while this one runs, a plain "open" just brings it back to front.
        if ! /usr/bin/xattr -p com.apple.quarantine "$real" >/dev/null 2>&1; then
          echo "handing over to $real"
          /usr/bin/nohup /bin/sh -c 'sleep 1; /usr/bin/open -n "$1"' _ "$real" >/dev/null 2>&1 &
          exit 0
        fi
      fi
    done
    fail "Move ProofJack to your Applications folder first, then open it from there." ;;
  (/Volumes/*|"$HOME/Downloads/"*)
    fail "Move ProofJack to your Applications folder first, then open it from there." ;;
esac
[ -f "$SRC/client.py" ] || [ $COMPILED = 1 ] || fail "This copy of ProofJack is incomplete. Download it again."

# 2. Python environment (development builds only; a release has its own Python inside).
if [ $COMPILED = 0 ]; then
if [ ! -x "$VPY" ] || ! "$VPY" -c "import fastapi, uvicorn, watchdog" >/dev/null 2>&1; then
  PY=""
  for c in python3.13 python3.12 python3.11 python3.10 python3; do
    if command -v "$c" >/dev/null 2>&1 && "$c" -c 'import sys; sys.exit(0 if sys.version_info >= (3,10) else 1)' 2>/dev/null; then PY="$(command -v "$c")"; break; fi
  done
  if [ -z "$PY" ]; then
    /usr/bin/open "https://www.python.org/downloads/macos/"
    fail "ProofJack needs Python 3.10 or newer. Install it from the page that just opened, then open ProofJack again."
  fi
  notify "Setting up for the first time. This takes about a minute."
  rm -rf "$VENV"
  "$PY" -m venv "$VENV" || fail "Could not create the Python environment. Details: ~/.proofjack/app.log"
  "$VENV/bin/pip" install -q --disable-pip-version-check --only-binary=cryptography -r "$SRC/requirements.txt" || fail "Could not install ProofJack's components. Check your internet connection and open ProofJack again."
fi
# 2b. Components added since the environment was made (cryptography: Pro license checks). Quietly, in the
#     background, so an update never holds up the window; Free works without them.
if ! "$VPY" -c "import cryptography" >/dev/null 2>&1; then
  ("$VENV/bin/pip" install -q --disable-pip-version-check --only-binary=cryptography -r "$SRC/requirements.txt" >>"$STATE/app.log" 2>&1 &)
fi
fi

# 3. Claude Code hooks, pointing at this copy of the app.
if ! hooks_ok; then
  pjrun install-hooks || fail "Could not connect to Claude Code. Details: ~/.proofjack/app.log"
  notify "Connected to Claude Code. New Claude Code sessions are recorded."
fi

# 3b. Editor extension (VS Code, Cursor). Installed in the background: the editors'
#     installers take up to a minute and must never hold up the window.
if [ -f "$APP/Contents/Resources/proofjack-sensor.vsix" ] && editor_missing_ext; then
  install_extensions &
fi

# 3c. The proofjack command: ~/.local/bin/proofjack. A development build runs it with ProofJack's own
#     venv (~/.proofjack/venv), which has the dependencies; a project's virtual environment is never used.
mkdir -p "$HOME/.local/bin"
if [ $COMPILED = 1 ]; then printf '#!/bin/sh\nexec "%s" cli "$@"\n' "$CORE" > "$HOME/.local/bin/proofjack"
else printf '#!/bin/sh\nexec "%s" "%s/pjcli.py" "$@"\n' "$VPY" "$SRC" > "$HOME/.local/bin/proofjack"; fi
chmod 755 "$HOME/.local/bin/proofjack"

# 4. Background service: install, or reload when this app is new, moved or updated.
STAMP="$STATE/installed"
if [ "$(cat "$STAMP" 2>/dev/null)" != "$VERSION $BUILD $SRC" ] || ! up; then
  log "reloading background service"
  pjrun service update >/dev/null || fail "Could not start the background service. Details: ~/.proofjack/app.log"
  for i in $(seq 1 40); do up && break; sleep 0.5; done
  up || fail "The background service did not start. Details: ~/.proofjack/proofjack.log"
  echo "$VERSION $BUILD $SRC" > "$STAMP"
  log "background service running"
  notify "ProofJack is running. It starts by itself when you log in."
fi

# 5. Live panel.
open_panel
echo "opened panel"
