#!/bin/bash
# PhoneForge macOS app launcher — no Terminal window; opens the web dashboard.

set -euo pipefail

# Clear download quarantine after the user has allowed first open (helps re-launches).
APP_BUNDLE="$(cd "$(dirname "$0")/../.." && pwd)"
/usr/bin/xattr -dr com.apple.quarantine "${APP_BUNDLE}" >/dev/null 2>&1 || true

APP_ROOT="$(cd "$(dirname "$0")/../Resources/phoneforge" && pwd)"
DATA_DIR="${HOME}/Library/Application Support/PhoneForge"
LOG_DIR="${HOME}/Library/Logs/PhoneForge"
PID_FILE="${LOG_DIR}/server.pid"
MARKER="${DATA_DIR}/.pf_app_installed"
PORT=8742
URL="http://localhost:${PORT}/d"

mkdir -p "${LOG_DIR}" "${DATA_DIR}"
export PHONEFORGE_DATA_DIR="${DATA_DIR}"
export PHONEFORGE_DB_PATH="${DATA_DIR}/phoneforge.db"
cd "${APP_ROOT}"

alert() {
  /usr/bin/osascript -e "display alert \"PhoneForge\" message \"$1\"" >/dev/null 2>&1 || true
}

notify() {
  /usr/bin/osascript -e "display notification \"$1\" with title \"PhoneForge\"" >/dev/null 2>&1 || true
}

if [[ "${APP_BUNDLE}" == *AppTranslocation* ]]; then
  notify "Tip: drag PhoneForge to Applications for faster launches."
fi

find_python() {
  if command -v python3 >/dev/null 2>&1; then
    command -v python3
    return 0
  fi
  for candidate in \
    "/Library/Frameworks/Python.framework/Versions/3.12/bin/python3" \
    "/Library/Frameworks/Python.framework/Versions/3.11/bin/python3" \
    "/usr/local/bin/python3"; do
    if [ -x "${candidate}" ]; then
      echo "${candidate}"
      return 0
    fi
  done
  return 1
}

PYTHON="$(find_python || true)"
if [ -z "${PYTHON}" ]; then
  alert "Python 3 is required. Install from https://www.python.org/downloads/ then open PhoneForge again."
  exit 1
fi

port_open() {
  /usr/sbin/lsof -ti ":${PORT}" >/dev/null 2>&1
}

stop_server() {
  if [ -f "${PID_FILE}" ]; then
    kill "$(cat "${PID_FILE}")" 2>/dev/null || true
    rm -f "${PID_FILE}"
  fi
  if port_open; then
    for pid in $(/usr/sbin/lsof -ti ":${PORT}" 2>/dev/null); do
      kill "${pid}" 2>/dev/null || true
    done
  fi
}

wait_for_server() {
  local i=0
  while [ "${i}" -lt 40 ]; do
    if port_open; then
      return 0
    fi
    sleep 0.25
    i=$((i + 1))
  done
  return 1
}

start_server() {
  if port_open; then
    return 0
  fi
  nohup "${PYTHON}" "${APP_ROOT}/server.py" >>"${LOG_DIR}/server.log" 2>&1 &
  echo $! >"${PID_FILE}"
  STARTED_BY_US=1
  wait_for_server
}

STARTED_BY_US=0

cleanup() {
  if [ "${STARTED_BY_US}" = "1" ]; then
    stop_server
  fi
}
trap cleanup EXIT INT TERM

if port_open; then
  /usr/bin/open "${URL}"
  exit 0
fi

if [ ! -f "${MARKER}" ]; then
  notify "First launch — installing dependencies (one time)…"
  if ! "${PYTHON}" "${APP_ROOT}/phoneforge.py" install >>"${LOG_DIR}/install.log" 2>&1; then
    alert "Install failed. Open ~/Library/Logs/PhoneForge/install.log for details."
    exit 1
  fi
  touch "${MARKER}"
  notify "Install complete."
fi

if ! start_server; then
  alert "Could not start PhoneForge on port ${PORT}. See ~/Library/Logs/PhoneForge/server.log"
  exit 1
fi

/usr/bin/open "${URL}"
notify "Dashboard opened in your browser. Keep PhoneForge running while your phone is plugged in."

# Stay alive so the Dock icon remains until the user quits the app.
while port_open; do
  sleep 2
done