#!/bin/bash
# Stop hook: block session from stopping if it has unreplied expects_reply messages.

OUIJA_PORT="${OUIJA_PORT:-7880}"
PANE="$TMUX_PANE"

if [ -z "$PANE" ]; then
    exit 0
fi

# Strip the leading % for the API path
PANE_NUM="${PANE#%}"

result=$(curl -sf "http://127.0.0.1:${OUIJA_PORT}/api/pane/${PANE_NUM}/pending-replies" 2>/dev/null)
if [ $? -ne 0 ]; then
    # Daemon not running or endpoint not available — don't block
    exit 0
fi

count=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('count', 0))" 2>/dev/null)

if [ "$count" -gt 0 ]; then
    senders=$(echo "$result" | python3 -c "
import sys, json
replies = json.load(sys.stdin).get('pending_replies', [])
print(', '.join(r['from'] for r in replies))
" 2>/dev/null)
    echo "You have $count unreplied message(s) from: $senders"
    echo "Use session_send to reply before stopping, or clear with session_send(expects_reply=false)."
    exit 2
fi

exit 0
