#!/bin/bash
# gremlet: make your desktop Gremlets react from the terminal, scripts, git hooks or test runners.
#
#   gremlet pass | fail | done | dance | wave | sleep | wake | special | water | stretch
#   gremlet focus [minutes]      start a focus session (they doze, then dance when the break starts)
#   gremlet unfocus              stop the focus timer
#   gremlet hide | show          hide them (e.g. before you present) / bring them back  (same as ⌃⌥G)
#   gremlet say "text" [seconds] the Gremlet nearest your cursor pops up with a speech bubble (default 8 s)
#   gremlet hobby [shelf|floor|<platform>]  the Gremlet nearest your cursor starts a window-box garden now; platforms:
#                                plank stone leaf cloud mushroom branch swing basket carpet treehouse snail
#   gremlet pair                 pair with your phone (opens a QR code to scan)
#   gremlet send [name]          send a Gremlet through the portal to your phone
#   gremlet status               what's out and whether a focus timer is running
#   gremlet meteors | festival | lanterns   start a little grove moment now
#   gremlet ferry | merchant     call the sky ferry, or the traveling merchant
#   gremlet ferry cross          the ferry makes one stop and sails through the doorway to the linked screen
#   gremlet snapshot             save a picture of your village (Pictures/Gremlets) and copy it
#   gremlet fullscreen [off]     preview how they tidy into the corners when an app is full screen (30 s)
#   gremlet plant                swap the corner plant for another one now
#   gremlet notch                someone climbs up to the home under the notch for a nap in the hammock
#   gremlet village-page [folder] a read-only web page of your village to put online (counts only, no project names)
#   gremlet wrapped [YYYY-MM]    the month with Claude Code as a poster (--sample to preview)
#   gremlet kite                 a free Gremlet flies a kite for a while
#   gremlet garden [water|snack|plant N]  the Focus Garden and today's snack (plant N: a test plant at stage N)
#   gremlet stairs | cart        build a block staircase up to a window / lay a minecart rail along a wide one
#   gremlet chest | expedition   hide a treasure chest somewhere high (someone goes to fetch it) / someone sets out for the highest point
#   gremlet moss [minutes]       how overgrown things are (preview: 0 to 300 minutes of Claude work; 0 clears it)
#   gremlet moss climb|pad|plant someone climbs a vine / weaves a platform into one / plants or waters moss now
#   gremlet sprout [daisy|mushroom|berries|dandelion]  something ready to pick comes up in the moss now
#   gremlet fireflies            a few fireflies come out over the moss (night or not), for a couple of minutes
#   gremlet critters             a ladybug, a bee and a little snail come out onto the moss
#   gremlet dock                 someone hops along your Dock icons (Play on the Dock)
#   gremlet bird                 a little bird drops by (bring the pointer near and it flies off)
#   gremlet postcard             a sample postcard in the mailbox under the porch (rest the pointer on it to read)
#   gremlet patch [ripe]         sow the vegetable patch by the nest hut now (ripe: ready to pick)
#   gremlet lanterns             someone sets a lantern out on the moss now
#   gremlet porch [leaves|snow|clear]   pile autumn leaves / snow on the nest hut (someone comes to sweep)
#   gremlet jar                  fireflies in the jar on the rain barrel now
#   gremlet seeds                seeds from a friend for the vegetable patch now
#   gremlet morningcard          yesterday's postcard in the mailbox now
#   gremlet home                 everyone waves goodbye and leaves the screen
#   gremlet family <name>        add every Gremlet in a family (animal, insect, dragon, dino, mythic, spirit, guardian, versionone, versiontwo)
#   gremlet nudge                the hanging home swings; whoever's inside comes out to wave
#   gremlet pantry [n]           what's in the pantry (or set it, 0-6), the care points, the house's stage
#   gremlet ask [idea] [name]    what the right-click menu does: with no idea, lists what each could do now
#   gremlet picnic|blanket       a lunchtime picnic now / a blanket brought over to you
#   gremlet quest                the launch quest list; quest done N | undo N | add TEXT | remove N | nag
#   gremlet friendseed           a friend's flower comes up in the moss (as if a friend's Gremlet brought a seed)
#   gremlet weather [sky|live]   the weather now; preview rain|drizzle|storm|snow|wind|clear for two minutes; live goes back
#   gremlet weather city <name>  get the real weather there (Open-Meteo); gremlet weather snowman: someone rolls one now
#   gremlet boost                two Gremlets team up: one boosts the other onto a window just out of reach
#   gremlet react screenshot|battery|plugged|offline|online   preview how they react to your Mac
#   gremlet link [right|left] [habitat-url]   link an iPad/phone screen on that edge (opens a QR); gremlet unlink; gremlet cross sends one over
#   gremlet season winter|spring|summer|autumn|auto   preview a season for ten minutes (trees, village, islands)
#   gremlet night on|off|auto    preview night (lanterns, fireflies, spirits) for ten minutes
#   gremlet timelapse [project]  stitch the daily village postcards into a video, or one tree's days into a GIF
#   gremlet forest               every project's tree on one hillside (Pictures/Gremlets), copied
#   gremlet recap [project]      the last Claude session as a card: tree before/after, numbers, minute strip (--sample to preview)
#   gremlet card [project]       save a card of a project's bonsai with its story (Pictures/Gremlets) and copy it
#   gremlet demo [seconds]       play a scripted Claude session on your front window and record it, plus a GIF (Movies/Gremlets)
#   gremlet grow [tasks]         count Claude tasks toward the grove by hand (default 1)
#   gremlet run <command...>     run a command, then pass/fail on its exit code (exit code is preserved)
#
# Talks to the Gremlets app on 127.0.0.1 only. Set GREMLETS_PORT if you changed the port.
PORT="${GREMLETS_PORT:-47920}"
URL="http://127.0.0.1:${PORT}"

call() {
  curl -s -m 2 -X "${2:-POST}" -H 'X-Gremlets: 1' "${URL}/$1" || { echo "gremlet: the Gremlets app isn't running" >&2; return 1; }
}

case "${1:-}" in
  pass|fail|done|dance|wave|sleep|wake|special|water|stretch) call "$1" >/dev/null ;;
  focus)   call "focus?minutes=${2:-25}" >/dev/null ;;
  unfocus) call unfocus >/dev/null ;;
  hide|show) call "$1" >/dev/null ;;
  say)
    [ -n "${2:-}" ] || { echo 'usage: gremlet say "text" [seconds]' >&2; exit 2; }
    curl -s -m 2 -G -X POST -H 'X-Gremlets: 1' --data-urlencode "text=$2" --data-urlencode "seconds=${3:-8}" "${URL}/say" >/dev/null \
      || { echo "gremlet: the Gremlets app isn't running" >&2; exit 1; } ;;
  hobby)
    q="hobby?"
    for a in "${@:2}"; do
      case "$a" in
        shelf) q="${q}shelf=1&" ;; floor) q="${q}shelf=0&" ;;
        plank|stone|leaf|cloud|mushroom|branch|swing|basket|carpet|treehouse|snail) q="${q}style=$a&" ;;
      esac
    done
    call "$q" >/dev/null ;;
  pair)    call phone/pair && echo && open "http://127.0.0.1:${PORT}/pair" ;;
  send)    curl -s -m 2 -G -X POST -H 'X-Gremlets: 1' --data-urlencode "name=${2:-}" "${URL}/phone/send"; echo ;;
  wish)    call wish >/dev/null && echo "✨" ;;   # shh
  status)  call status GET; echo ;;
  ferry)   if [ "${2:-}" = "cross" ]; then call "ferry?cross=1"; echo; else call ferry >/dev/null; fi ;;
  merchant) call merchant >/dev/null ;;
  kite)    call kite; echo ;;
  stairs|cart|chest|expedition|unlink|cross|boost|notch|plant) call "$1"; echo ;;
  react)   call "react?name=${2:-screenshot}"; echo ;;
  sprout)  call "sprout?kind=${2:-}"; echo ;;
  fireflies) call fireflies; echo ;;
  critters) call critters; echo ;;
  dock) call dock; echo ;;
  bird)    call bird; echo ;;
  postcard) call postcard; echo ;;
  patch)   if [ "${2:-}" = ripe ]; then call "patch?ripe=1"; else call patch; fi; echo ;;
  lanterns) call lanterns; echo ;;
  porch)   call "porch?what=${2:-leaves}"; echo ;;
  jar)     call jar; echo ;;
  seeds)   call seeds; echo ;;
  morningcard) call morningcard; echo ;;
  home)    call home; echo ;;
  family)  call "family?name=${2:-}"; echo ;;
  nudge)   call nudge; echo ;;
  pantry)  if [ -n "${2:-}" ]; then call "pantry?n=${2}"; else call pantry; fi; echo ;;
  ask)     curl -s -m 2 -G -X POST -H 'X-Gremlets: 1' --data-urlencode "idea=${2:-}" --data-urlencode "name=${3:-}" "${URL}/ask"; echo ;;
  picnic|blanket|friendseed) call "$1"; echo ;;
  quest)   case "${2:-}" in
             done|undo|remove) call "quest?do=$2&n=${3:-0}" ;;
             add) shift 2; curl -s -m 2 -G -X POST -H 'X-Gremlets: 1' --data-urlencode "do=add" --data-urlencode "text=$*" "${URL}/quest" ;;
             nag) call "quest?do=nag" ;;
             *) call quest ;;
           esac ;;
  moss)    case "${2:-}" in
             climb|pad|plant) call "moss?do=$2" ;;
             "") call moss ;;
             *) call "moss?minutes=$2" ;;
           esac; echo ;;
  village-page) curl -s -m 20 -G -X POST -H 'X-Gremlets: 1' --data-urlencode "dir=${2:-}" "${URL}/village-page"; echo ;;
  fullscreen) if [ "${2:-}" = "off" ]; then call "compact?off=1"; else call compact; fi; echo ;;
  weather) case "${2:-}" in
             "") call weather ;;
             snowman) call "weather?do=snowman" ;;
             city) shift 2; curl -s -m 5 -G -X POST -H 'X-Gremlets: 1' --data-urlencode "city=$*" "${URL}/weather" ;;
             *) call "weather?sky=$2" ;;
           esac; echo ;;
  link)    curl -s -m 5 -G -X POST -H 'X-Gremlets: 1' --data-urlencode "side=${2:-right}" --data-urlencode "habitat=${3:-}" "${URL}/link"; echo; open "http://127.0.0.1:${PORT}/link" ;;
  wrapped) if [ "${2:-}" = "--sample" ]; then curl -s -m 20 -X POST -H 'X-Gremlets: 1' "${URL}/wrapped?sample=1"; else curl -s -m 20 -G -X POST -H 'X-Gremlets: 1' --data-urlencode "month=${2:-}" "${URL}/wrapped"; fi; echo ;;
  snapshot) call snapshot; echo; echo 'Caption idea: "My desktop village so far. Every building is a Claude Code session, every plant grew from a finished task."' ;;
  season)  call "season?name=${2:-auto}"; echo ;;
  night)   call "night?on=${2:-auto}"; echo ;;
  timelapse) curl -s -m 120 -G -X POST -H 'X-Gremlets: 1' --data-urlencode "project=${2:-}" "${URL}/timelapse"; echo ;;
  recap)   if [ "${2:-}" = "--sample" ]; then curl -s -m 10 -X POST -H 'X-Gremlets: 1' "${URL}/recap?sample=1"; else curl -s -m 10 -G -X POST -H 'X-Gremlets: 1' --data-urlencode "project=${2:-}" "${URL}/recap"; fi; echo ;;
  forest)  call forest; echo; echo 'Caption idea: "Every project I have worked on with Claude Code, as a tree. The big ones are the ones I kept coming back to."' ;;
  card)    curl -s -m 5 -G -X POST -H 'X-Gremlets: 1' --data-urlencode "project=${2:-}" "${URL}/card"; echo
           echo 'Caption idea: "This bonsai is my project. A branch per Claude Code session, a leaf per file edit, a flower per task, fruit when the tests pass."' ;;
  demo)
    secs="${2:-42}"
    out="$(curl -s -m 2 -X POST -H 'X-Gremlets: 1' "${URL}/demo?seconds=${secs}&pid=$PPID")" || { echo "gremlet: the Gremlets app isn't running" >&2; exit 1; }
    region="$(printf '%s' "$out" | /usr/bin/python3 -c 'import json,sys
try: print(json.load(sys.stdin).get("region",""))
except Exception: print("")')"
    [ -n "$region" ] || { echo "gremlet: $out" >&2; exit 1; }
    if [ "${3:-}" = "--no-record" ]; then echo "Playing a ${secs}s Claude session demo."; exit 0; fi
    mkdir -p "$HOME/Movies/Gremlets"
    f="$HOME/Movies/Gremlets/Claude session $(date '+%Y-%m-%d %H.%M').mov"
    echo "Recording ${secs}s of the front window to $f"
    screencapture -V "$secs" -R "$region" "$f" && echo "Saved: $f"
    gif="$(curl -s -m 120 -G -X POST -H 'X-Gremlets: 1' --data-urlencode "path=$f" "${URL}/gif" | /usr/bin/python3 -c 'import json,sys
try: print(json.load(sys.stdin).get("path",""))
except Exception: print("")')"
    [ -n "$gif" ] && echo "GIF:   $gif" ;;
  meteors|festival|lanterns) call "event?kind=$1" >/dev/null ;;
  grow)    call "grove/feed?tasks=${2:-1}"; echo ;;
  garden)  case "${2:-}" in
             water|snack) call "garden?do=$2" ;;
             plant) call "garden?do=plant&stage=${3:-4}" ;;
             *) call garden ;;
           esac; echo ;;
  run)
    shift
    [ $# -gt 0 ] || { echo "usage: gremlet run <command...>" >&2; exit 2; }
    "$@"; code=$?
    if [ $code -eq 0 ]; then call pass >/dev/null; else call fail >/dev/null; fi
    exit $code ;;
  ""|-h|--help|help) sed -n '2,29p' "$0" | sed 's/^# \{0,1\}//' ;;
  *) echo "gremlet: unknown action '$1' (try: gremlet help)" >&2; exit 2 ;;
esac
