#!/bin/bash
# Airport TSA wait time monitor — TPA, JFK, EWR
# Posts to Discord DM via OpenClaw HTTP gateway
# Schedule: 6am, 10am, 2pm, 6pm, 10pm ET through Fri Mar 27 2026

BIRD="/home/johan/clawd/scripts/bird"
OC_URL="http://localhost:18789"
DISCORD_USER="johanjongsma"
LOG="/home/johan/clawd/memory/airport-wait-log.md"
TIMESTAMP=$(date '+%a %b %d, %I:%M %p ET')
NEXT_TIMES="6am · 10am · 2pm · 6pm · 10pm ET"

echo "" >> "$LOG"
echo "=== $TIMESTAMP ===" >> "$LOG"

# ---- Web scrape wait times ----
TPA_WEB=$(curl -s --max-time 10 "https://www.tsawaittimes.com/airport/TPA" 2>/dev/null | grep -oi '[0-9]\+ min' | head -1)
JFK_WEB=$(curl -s --max-time 10 "https://www.tsawaittimes.com/airport/JFK" 2>/dev/null | grep -oi '[0-9]\+ min' | head -1)
EWR_WEB=$(curl -s --max-time 10 "https://www.tsawaittimes.com/airport/EWR" 2>/dev/null | grep -oi '[0-9]\+ min' | head -1)

# ---- X/Twitter search ----
TPA_X=$("$BIRD" search "TPA Tampa airport TSA security wait" --max-results 3 2>/dev/null | grep -i "wait\|min\|hour\|line\|TSA" | head -3 | tr '\n' ' ')
JFK_X=$("$BIRD" search "JFK airport TSA security wait" --max-results 3 2>/dev/null | grep -i "wait\|min\|hour\|line\|TSA" | head -3 | tr '\n' ' ')
EWR_X=$("$BIRD" search "EWR Newark airport TSA security wait" --max-results 3 2>/dev/null | grep -i "wait\|min\|hour\|line\|TSA" | head -3 | tr '\n' ' ')

# ---- News: government shutdown / travel chaos ----
SHUTDOWN_NEWS=$(curl -s --max-time 10 "https://news.google.com/rss/search?q=TSA+airport+wait+government+shutdown&hl=en-US&gl=US&ceid=US:en" 2>/dev/null | grep -o '<title>[^<]*</title>' | sed 's/<[^>]*>//g' | grep -iv "google news" | head -3 | tr '\n' ' | ')

# ---- Format output ----
TPA_LINE="${TPA_WEB:-N/A}"
JFK_LINE="${JFK_WEB:-N/A}"
EWR_LINE="${EWR_WEB:-N/A}"

# Log raw data
echo "TPA web: $TPA_WEB | X: $TPA_X" >> "$LOG"
echo "JFK web: $JFK_WEB | X: $JFK_X" >> "$LOG"
echo "EWR web: $EWR_WEB | X: $EWR_X" >> "$LOG"
echo "News: $SHUTDOWN_NEWS" >> "$LOG"

# Build context note
CONTEXT=""
[ -n "$TPA_X" ] && CONTEXT="TPA social: $TPA_X"
[ -n "$SHUTDOWN_NEWS" ] && CONTEXT="${CONTEXT:+$CONTEXT | }News: $(echo "$SHUTDOWN_NEWS" | cut -c1-200)"

MSG="✈️ **Airport Security Wait Update** — $TIMESTAMP

🔵 **TPA** (Tampa → Tanya departs Wed Mar 25): ${TPA_LINE}
🟡 **JFK** (New York — Tanya arrives Wed Mar 25): ${JFK_LINE}
🟢 **EWR** (Newark — Johan departs Fri Mar 27): ${EWR_LINE}"

if [ -n "$CONTEXT" ]; then
  MSG="$MSG

📌 $CONTEXT"
fi

MSG="$MSG

_Updates: $NEXT_TIMES_"

# Post via OC gateway (Discord DM)
curl -s -X POST "$OC_URL/api/message/send" \
  -H "Content-Type: application/json" \
  -d "{\"channel\":\"discord\",\"target\":\"$DISCORD_USER\",\"message\":$(echo "$MSG" | python3 -c 'import sys,json; print(json.dumps(sys.stdin.read()))')}" \
  >> "$LOG" 2>&1

echo "Posted at $TIMESTAMP" >> "$LOG"
