#!/usr/bin/env bash
# Priority Forge sessionStart hook (plugin-bundled).
# Ensures the backend at :3456 is reachable when a Cursor session starts.
# Safe to re-run; never blocks session startup — max wall time ~2s.
#
# Unlike the installer-written hook, this one does not have the repo path
# baked in — it reads the discovery file written by `./setup.sh install` or
# `./setup.sh install-cursor-plugin`. If the discovery file is missing, the
# plugin can still kick the persistent service but cannot fall back to
# nohup-starting the backend; the user will see status "repo-path-missing".

set -u

HEALTH_URL="http://127.0.0.1:3456/health"

if [ "$(uname -s)" = "Darwin" ]; then
  DISCOVERY_FILE="$HOME/Library/Application Support/priority-forge/repo-path"
else
  DISCOVERY_FILE="$HOME/.local/share/priority-forge/repo-path"
fi

emit() { printf '{"priority-forge":"%s"}\n' "$1"; }

if curl -fsS --max-time 1 "$HEALTH_URL" >/dev/null 2>&1; then
  emit "already-running"
  exit 0
fi

if command -v systemctl >/dev/null 2>&1; then
  if systemctl --user start priority-forge-backend >/dev/null 2>&1; then
    emit "service-kicked-systemd"
    exit 0
  fi
fi

if command -v launchctl >/dev/null 2>&1; then
  if launchctl kickstart "gui/$(id -u)/com.priority-forge.backend" >/dev/null 2>&1; then
    emit "service-kicked-launchd"
    exit 0
  fi
fi

if [ -f "$DISCOVERY_FILE" ]; then
  PRIORITY_FORGE_DIR=$(cat "$DISCOVERY_FILE" | tr -d '\r\n')
  if [ -x "$PRIORITY_FORGE_DIR/setup.sh" ]; then
    nohup bash "$PRIORITY_FORGE_DIR/setup.sh" start:backend >/dev/null 2>&1 &
    disown 2>/dev/null || true
    emit "nohup-fallback"
    exit 0
  fi
fi

if [ ! -f "$DISCOVERY_FILE" ]; then
  emit "repo-path-missing"
else
  emit "failed"
fi
exit 0
