#!/bin/bash
# Distributable launcher — GUI-safe, fully self-contained (no ~/.claude reference).
# Lives inside the .app at Contents/Resources/engine/launch.sh next to the engine.
# Detaches the render into a background worker so the app returns instantly (a
# synchronous render made the app beachball / "hang" on big folders); the worker
# (nohup, reparented to launchd) renders, opens the tool, and notifies on failure.
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

DIR="$(cd "$(dirname "$0")" && pwd)"
ENGINE="$DIR/triage_app.py"
OUTDIR="$HOME/Triage Review and Compare"
mkdir -p "$OUTDIR"
LOG="$OUTDIR/.last-run.log"

PY="/usr/bin/python3"
[ -x "$PY" ] || PY="$(command -v python3)"

if [ "$1" = "--worker" ]; then
  shift
  if [[ " $* " == *" --loading-file "* ]]; then
    "$PY" "$ENGINE" "$@" >"$LOG" 2>&1
  else
    "$PY" "$ENGINE" --loading "$@" >"$LOG" 2>&1
  fi
  code=$?
  if [ "$code" -ne 0 ]; then
    msg="$(tail -n 1 "$LOG" | sed 's/"/\\"/g')"
    [ -z "$msg" ] && msg="See $LOG"
    /usr/bin/osascript -e "display notification \"$msg\" with title \"PageHawk could not open this\"" >/dev/null 2>&1
  fi
  exit "$code"
fi

nohup /bin/bash "$0" --worker "$@" >/dev/null 2>&1 </dev/null &
exit 0
