#!/usr/bin/env bash
set -euo pipefail

API_BASE="https://api.farpy.com/node/v1"
BASE="$HOME/Library/Application Support/Farpy/NodeMuncher"
BIN="$BASE/bin"
PLIST="$HOME/Library/LaunchAgents/com.farpy.nodemuncher.plist"

mkdir -p "$BIN"

# agent (background heartbeat + prints current mode)
cat >"$BIN/nodemuncher-agent.sh" <<'EAG'
#!/usr/bin/env bash
set -euo pipefail
API_BASE="https://api.farpy.com/node/v1"
while true; do
  curl -fsS -m 8 -X POST "$API_BASE/heartbeat" -H "content-type: application/json" -d "{}" >/dev/null 2>&1 || true
  CFG="$(curl -fsS -m 8 "$API_BASE/config" 2>/dev/null || true)"
  if [ -n "${CFG:-}" ]; then
    MODE="$(printf "%s" "$CFG" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("mode","?"))' 2>/dev/null || echo "?")"
    NOTE="$(printf "%s" "$CFG" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("caps",{}).get("note",""))' 2>/dev/null || echo "")"
    echo "NODEMUNCHER mode=$MODE $NOTE"
  fi
  sleep 20
done
EAG
chmod 755 "$BIN/nodemuncher-agent.sh"

# mode helper
cat >"$BIN/set-mode.sh" <<'EOM'
#!/usr/bin/env bash
set -euo pipefail
MODE="${1:-}"
case "$MODE" in
  chill|normal|whoa) ;;
  *) echo "ERR: usage: set-mode.sh chill|normal|whoa" >&2; exit 2 ;;
esac
API="https://api.farpy.com/node/v1/mode"
curl -fsS -m 8 -X POST "$API" -H "content-type: application/json" -d "{\"mode\":\"$MODE\"}"
echo
EOM
chmod 755 "$BIN/set-mode.sh"

# launchd agent (no admin)
mkdir -p "$HOME/Library/LaunchAgents"
cat >"$PLIST" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>Label</key><string>com.farpy.nodemuncher</string>
    <key>ProgramArguments</key>
    <array><string>$BIN/nodemuncher-agent.sh</string></array>
    <key>RunAtLoad</key><true/>
    <key>KeepAlive</key><true/>
    <key>StandardOutPath</key><string>$BASE/nodemuncher.log</string>
    <key>StandardErrorPath</key><string>$BASE/nodemuncher.err</string>
  </dict>
</plist>
EOF

launchctl unload "$PLIST" >/dev/null 2>&1 || true
launchctl load "$PLIST" >/dev/null 2>&1 || true

echo "OK: NodeMuncher installed (mac user mode)."
echo "Mode: $BIN/set-mode.sh chill|normal|whoa"
echo "Logs: $BASE/nodemuncher.log"
