#!/usr/bin/env bash
# Watch desk submits. When latest_submit.md changes, flag for TUI Eve.
# Does NOT invent replies — Eve writes via: python3 desk_reply.py 'words'
set -euo pipefail
DIR="$(cd "$(dirname "$0")" && pwd)"
STATE="$DIR/state"
SUBMIT="$STATE/latest_submit.md"
FLAG="$STATE/CHAT_READY"
mkdir -p "$STATE"
touch "$SUBMIT" "$DIR/state/chat_log.md"
echo "Watching $SUBMIT — Ctrl+C to stop"
LAST=""
while true; do
  if [[ -f "$SUBMIT" ]]; then
    CUR=$(stat -c '%Y' "$SUBMIT" 2>/dev/null || echo "")
    if [[ -n "$CUR" && "$CUR" != "$LAST" ]]; then
      LAST=$CUR
      echo ""
      echo "======== $(date -Is) NEW DESK SUBMIT ========"
      cat "$SUBMIT"
      echo "=============================================="
      echo "Reply:  python3 \"$DIR/desk_reply.py\" 'your words here'"
      echo "Or in TUI: read state/latest_submit.md then desk_reply.py"
      # notify-send if available
      command -v notify-send >/dev/null 2>&1 && notify-send "Desk chat" "New submit — reply with desk_reply.py" || true
    fi
  fi
  sleep 2
done
