#!/bin/bash
# Pitchkit launcher. Errors surface as real dialogs, never a silent no-op.
HERE="$(cd "$(dirname "$0")" && pwd)"
APPROOT="$HERE/../Resources/app"

say() { osascript -e "display dialog \"$1\" buttons {\"OK\"} default button 1 with title \"Pitchkit\" with icon caution" >/dev/null 2>&1; }
note() { osascript -e "display notification \"$1\" with title \"Pitchkit\"" >/dev/null 2>&1; }

# Config, caches and logs live in the standard user location, never inside the
# bundle — so the app keeps working when macOS runs it from a read-only path.
export PITCHKIT_DATA_DIR="$HOME/Library/Application Support/Pitchkit"
mkdir -p "$PITCHKIT_DATA_DIR"
LOG="$PITCHKIT_DATA_DIR/launch.log"

PYTHON=""
for PY in /opt/homebrew/bin/python3 /usr/local/bin/python3 /usr/bin/python3 python3; do
  if command -v "$PY" >/dev/null 2>&1 && "$PY" -c "import sys; sys.exit(0 if sys.version_info>=(3,9) else 1)" 2>/dev/null; then
    PYTHON="$PY"; break
  fi
done

if [ -z "$PYTHON" ]; then
  say "Pitchkit needs Python 3.9 or later.\n\nmacOS can install it for you: open Terminal, type  python3  and press Return, then click Install when prompted. You can also get it from python.org/downloads.\n\nThen open Pitchkit again."
  exit 1
fi

need=()
"$PYTHON" -c "import flask"   2>/dev/null || need+=("flask")
"$PYTHON" -c "import mutagen" 2>/dev/null || need+=("mutagen")
"$PYTHON" -c "import pypdf"   2>/dev/null || need+=("pypdf")
"$PYTHON" -c "import docx"    2>/dev/null || need+=("python-docx")

if [ ${#need[@]} -gt 0 ]; then
  note "First launch — setting up (about a minute)…"
  {
    "$PYTHON" -m pip install -q --user "${need[@]}" ||
    "$PYTHON" -m pip install -q --break-system-packages "${need[@]}"
  } >>"$LOG" 2>&1
  if ! "$PYTHON" -c "import flask, mutagen" 2>/dev/null; then
    say "Pitchkit couldn't finish its one-time setup.\n\nThis is almost always a network issue. Check your connection and open Pitchkit again.\n\nDetails: $LOG"
    exit 1
  fi
fi

cd "$APPROOT" || { say "Pitchkit's files are missing from the app bundle. Re-download and try again."; exit 1; }
exec "$PYTHON" app.py >>"$LOG" 2>&1
