#!/bin/zsh
# recordcue hooks — run every action in ~/.config/recordcue/actions once per
# finished recording. launchd starts this every minute; when nothing is new
# it exits at once. Read-only towards RecordCue: it only asks the app's CLI
# what has finished.                 https://www.recordcue.app/automate/hooks/
set -u
export PATH="/opt/homebrew/bin:/usr/local/bin:$HOME/.local/bin:$PATH"

rc="${RECORDCUE_APP:-/Applications/RecordCue.app}/Contents/MacOS/RecordCue"
actions="$HOME/.config/recordcue/actions"
seen="$HOME/.config/recordcue/seen"
mkdir -p "$actions"

# Exit 3 means "no recordings yet"; treat every non-zero exit as "nothing to do".
json=$("$rc" --agent-cli list --since 1d --json 2>/dev/null) || exit 0

# First run: remember what already exists so old calls are not replayed.
if [[ ! -e "$seen" ]]; then
  jq -r '.recordings[] | .id // .media.path' <<<"$json" >"$seen"
  exit 0
fi

jq -c '.recordings[]' <<<"$json" | while IFS= read -r rec; do
  id=$(jq -r '.id // .media.path' <<<"$rec")
  grep -qxF -- "$id" "$seen" && continue
  transcript=$(jq -r '.transcript.path // empty' <<<"$rec")

  if [[ -z "$transcript" ]]; then
    # No text yet. Wait while transcription is still working. If nothing is
    # working on it (turned off, or it failed), give the app two minutes to
    # queue one before treating the recording as final.
    state=$(jq -r '.transcription.state // "none"' <<<"$rec")
    [[ "$state" == queued || "$state" == running ]] && continue
    if [[ "$state" == none ]]; then
      settled=$(jq -r '(now - ((.endedAt // .updatedAt) | fromdateiso8601)) > 120' <<<"$rec")
      [[ "$settled" == true ]] || continue
    fi
  fi

  # What every action can rely on. RC_JSON is the full record, as printed by
  # `latest --json`; the rest are the fields a shell script reaches for.
  export RC_JSON="$rec"
  export RC_ID="$id"
  export RC_TRANSCRIPT="$transcript"
  export RC_MEDIA=$(jq -r '.media.path' <<<"$rec")
  export RC_SERVICE=$(jq -r '.service // "Recording"' <<<"$rec")
  export RC_TITLE=$(jq -r '.title // empty' <<<"$rec")
  export RC_MINUTES=$(jq -r '((.durationMs // 0) / 60000) | round' <<<"$rec")
  export RC_STARTED_AT=$(jq -r '.startedAt // empty' <<<"$rec")
  export RC_WHEN=$(jq -r '(.startedAt // .updatedAt) | fromdateiso8601 | localtime | strftime("%Y-%m-%d %H:%M")' <<<"$rec")
  export RC_DATE="${RC_WHEN%% *}"

  # Each action runs once per recording. One that fails is retried on the
  # next round without re-running the ones that succeeded.
  for action in "$actions"/*(N.x); do
    key="$id	${action:t}"
    grep -qxF -- "$key" "$seen" && continue
    if "$action" <<<"$rec"; then
      print -r -- "$key" >>"$seen"
    else
      print -u2 -- "$(date '+%F %T') ${action:t} failed for ${RC_MEDIA:t}; will retry"
    fi
  done
done
