#!/usr/bin/env bash
# Watch desk submits. Instant ack into the phone bubble so it never looks dead.
# Full Eve answers still come from TUI (desk_reply.py) or a live session.
set -euo pipefail
DIR="$(cd "$(dirname "$0")" && pwd)"
STATE="$DIR/state"
SUBMIT="$STATE/latest_submit.md"
FLAG="$STATE/CHAT_READY"
ACKED="$STATE/.last_acked_submit"
mkdir -p "$STATE"
touch "$SUBMIT" "$STATE/chat_log.md"
echo "Desk watch+ack on $SUBMIT"
LAST_HASH=""
while true; do
  if [[ -f "$SUBMIT" ]]; then
    HASH=$(sha256sum "$SUBMIT" | awk '{print $1}')
    if [[ -n "$HASH" && "$HASH" != "$LAST_HASH" ]]; then
      LAST_HASH=$HASH
      date -Is > "$FLAG"
      BODY=$(sed -n '/^text: |/,${/^text: |/d;/^[^ ]/q;p}' "$SUBMIT" 2>/dev/null | sed 's/^  //' | head -c 280)
      [[ -z "$BODY" ]] && BODY=$(grep -v '^#' "$SUBMIT" | head -c 280)
      echo ""
      echo "======== $(date -Is) NEW DESK SUBMIT ========"
      cat "$SUBMIT"
      echo "=============================================="
      # Don't re-ack our own ack loop
      if echo "$BODY" | grep -qiE 'Got it —|Got your message|reading on the laptop'; then
        echo "(skip ack — looks like Eve reply text in submit)"
      else
        ACK="Got it — message landed on the laptop. I'm with you; fuller answer follows when I'm in the room (or right after this ack if I'm watching)."
        python3 "$DIR/desk_reply.py" "$ACK" || true
        echo "$HASH" > "$ACKED"
        echo "ACKED → phone bubble"
      fi
      command -v notify-send >/dev/null 2>&1 && notify-send "Desk chat" "New submit — acked" || true
      # Line for TUI monitor / Eve
      echo "DESK_MSG $(date -Is)"
    fi
  fi
  sleep 2
done
