#!/bin/bash
set -e
source /tmp/claude-1000/-home-tperm-code-discord-bot/2d0c449f-83aa-4e0f-941c-184bec2661bf/scratchpad/bot.env
CHANNEL=1459784350164848722
OUT=/tmp/claude-1000/-home-tperm-code-discord-bot/2d0c449f-83aa-4e0f-941c-184bec2661bf/scratchpad/agentnews
mkdir -p "$OUT"
rm -f "$OUT"/raw_*.json
before=""
page=0
while true; do
  if [ -z "$before" ]; then
    url="https://discord.com/api/v10/channels/$CHANNEL/messages?limit=100"
  else
    url="https://discord.com/api/v10/channels/$CHANNEL/messages?limit=100&before=$before"
  fi
  resp=$(curl -sL -H "Authorization: Bot $DISCORD_TOKEN" "$url")
  echo "$resp" > "$OUT/raw_$page.json"
  count=$(echo "$resp" | python3 -c "import json,sys; d=json.load(sys.stdin); print(len(d) if isinstance(d,list) else -1)")
  if [ "$count" -le 0 ]; then
    echo "done, page $page count $count"
    break
  fi
  # get last message id (oldest, since discord returns newest first) and its timestamp
  last_id=$(echo "$resp" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d[-1]['id'])")
  last_ts=$(echo "$resp" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d[-1]['timestamp'])")
  echo "page $page count $count last_ts $last_ts"
  before=$last_id
  page=$((page+1))
  # stop if last_ts predates 2026-10-07
  if [[ "$last_ts" < "2026-10-07T00:00:00" ]]; then
    echo "reached cutoff"
    break
  fi
  sleep 0.3
done
