#!/bin/bash
# Daily AI Newsletter Digest - Fast Reliable Version
set -e

EMAIL_SKILL="/home/openclaw/.openclaw/workspace/skills/imap-smtp-email"
OUTPUT_FILE="/tmp/ai-newsletter-emails.json"

echo "🤖 Daily AI Newsletter Digest" >&2
echo "============================================================" >&2
echo "$(date)" >&2
echo "" >&2

echo "🔍 Searching for AI newsletters from last 48 hours..." >&2

# Single search for all recent emails, then filter locally
cd "$EMAIL_SKILL"

# Get recent emails and filter for AI newsletters (expanded to 48h and more sources)
ALL_EMAILS=$(node scripts/imap.js search --recent 48h --limit 100 2>/dev/null | jq '[.[] | select(.from | test("AI Valley|AI Secret|DeepView|Deep View|The Rundown|TLDR|Benedict|aivalley|aisecret|deepview|therundown|tldr|benedict"; "i"))]' 2>/dev/null || echo "[]")

# Save results
echo "$ALL_EMAILS" > "$OUTPUT_FILE"

EMAIL_COUNT=$(echo "$ALL_EMAILS" | jq '. | length')
echo "" >&2
echo "🎯 Found $EMAIL_COUNT AI-related emails" >&2

if [ "$EMAIL_COUNT" -eq 0 ]; then
  echo "No new AI newsletters in the last 24 hours." >&2
  echo "[]"
  exit 0
fi

echo "" >&2
echo "📧 Ready to process $EMAIL_COUNT newsletters" >&2

# Output the emails
cat "$OUTPUT_FILE"
