#!/bin/bash
# AI Newsletter Digest - Fetch and analyze
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
EMAIL_SKILL="$SCRIPT_DIR/../../skills/imap-smtp-email"

echo "🤖 AI Newsletter Digest Generator" >&2
echo "============================================================" >&2

# Fetch AI-related emails from last 7 days
echo "📧 Fetching AI newsletters from last 7 days..." >&2

python3 "$EMAIL_SKILL/scripts/imap-py.py" search \
  --subject "AI" \
  --recent 7d \
  --limit 20 > /tmp/ai_emails_list.txt

# Count how many we found
EMAIL_COUNT=$(grep -c "^●" /tmp/ai_emails_list.txt || echo "0")
echo "🎯 Found $EMAIL_COUNT AI-related emails" >&2

if [ "$EMAIL_COUNT" = "0" ]; then
  echo "No AI newsletters found in the last 7 days."
  exit 0
fi

# Extract UIDs
UIDS=$(grep "UID:" /tmp/ai_emails_list.txt | awk '{print $3}' | head -10)

echo "📖 Fetching content from top 10 newsletters..." >&2
echo "" > /tmp/ai_newsletters_content.txt

for uid in $UIDS; do
  echo "  • Fetching email $uid..." >&2
  python3 "$EMAIL_SKILL/scripts/imap-py.py" fetch "$uid" >> /tmp/ai_newsletters_content.txt 2>/dev/null || true
  echo -e "\n\n========================================\n\n" >> /tmp/ai_newsletters_content.txt
done

echo "✅ Content fetched!" >&2
echo "" >&2
echo "📋 Newsletter sources:" >&2
grep "^From:" /tmp/ai_newsletters_content.txt | sort -u | head -10 >&2
echo "" >&2

# Output the file path for the agent to analyze
echo "/tmp/ai_newsletters_content.txt"
