#!/bin/bash
#
# OpenClaw Daily Intelligence Briefing
# Runs daily at lunchtime (Perth time)
# - Queries FreshRSS for OpenClaw-related articles
# - Searches web for OpenClaw news, Reddit posts
# - Sends highlights to Telegram + email summary
#

set -e

# Configuration
FRESHRSS_URL="http://freshrss.kangaroo-eel.ts.net"
SKILL_DIR="/home/openclaw/.openclaw/workspace/skills/freshrss-reader"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_FILE="/tmp/openclaw-digest-$(date +%Y%m%d).log"

# SendClaw credentials for email
SENDCLAW_API_KEY="sk_15000b789ec9a820f785681a4115396bd22c028e08c652e0"
SENDCLAW_FROM="krilly@sendclaw.com"

# Telegram chat ID for Anthony
TELEGRAM_CHAT="telegram:1793951355"

# User's email
USER_EMAIL="anthony@anthony-martin.com"

echo "=== OpenClaw Daily Digest - $(date) ===" | tee -a "$LOG_FILE"

# ============================================
# STEP 1: Get FreshRSS headlines from last 24 hours
# ============================================
echo "📰 Fetching FreshRSS headlines..." | tee -a "$LOG_FILE"

# Get recent headlines (last 24 hours = 24 hours)
FRESHRSS_OUTPUT=$("${SKILL_DIR}/scripts/freshrss.sh" headlines --hours 24 --count 50 2>/dev/null || echo "")

if [ -z "$FRESHRSS_OUTPUT" ] || [ "$FRESHRSS_OUTPUT" = "Error: FRESHRSS_URL, FRESHRSS_USER, and FRESHRSS_API_PASSWORD must be set" ]; then
    echo "⚠️ FreshRSS not configured or no articles found" | tee -a "$LOG_FILE"
    FRESHRSS_MATCHES=""
else
    # Filter for OpenClaw-related content (case insensitive)
    FRESHRSS_MATCHES=$(echo "$FRESHRSS_OUTPUT" | grep -i -E '(openclaw|clawdbot|clawhub|clawflows)' || true)
    
    # Also include AI/LLM agent related content that might be relevant
    FRESHRSS_AI=$(echo "$FRESHRSS_OUTPUT" | grep -i -E '(ai agent|llm agent|autonomous agent|claude code|cursor agent|coding agent)' | head -5 || true)
    
    echo "Found $(echo "$FRESHRSS_MATCHES" | grep -c '^\[' || echo 0) OpenClaw-specific articles" | tee -a "$LOG_FILE"
    echo "Found $(echo "$FRESHRSS_AI" | grep -c '^\[' || echo 0) AI agent articles" | tee -a "$LOG_FILE"
fi

# ============================================
# STEP 2: Search web for OpenClaw news
# ============================================
echo "🌐 Searching web for OpenClaw news..." | tee -a "$LOG_FILE"

# Use brave search via web_search tool through OpenClaw CLI if available
# For now, we'll construct search URLs that can be opened
REDDIT_SEARCH_URL="https://www.reddit.com/search/?q=openclaw&type=posts&t=day"
GITHUB_SEARCH_URL="https://github.com/search?q=openclaw&type=repositories&s=updated&o=desc"
WEB_SEARCH_URL="https://www.google.com/search?q=openclaw+ai+agent+news&tbs=qdr:d"

# ============================================
# STEP 3: Compile the digest
# ============================================
echo "📝 Compiling digest..." | tee -a "$LOG_FILE"

# Create Telegram message (concise)
TELEGRAM_MSG="🦀 *OpenClaw Daily Briefing* — $(date '+%a, %b %d')

"

if [ -n "$FRESHRSS_MATCHES" ]; then
    TELEGRAM_MSG+="📰 *FreshRSS Highlights:*

"
    # Format for Telegram (limit to top 5)
    echo "$FRESHRSS_MATCHES" | head -5 | while read -r line; do
        if [[ "$line" =~ ^\[.*\] ]]; then
            TELEGRAM_MSG+="• ${line:0:200}...
"
        fi
    done
    TELEGRAM_MSG+="
"
fi

# Add quick links section
TELEGRAM_MSG+="🔍 *Quick Searches:*
"
TELEGRAM_MSG+="• [Reddit](${REDDIT_SEARCH_URL})
"
TELEGRAM_MSG+="• [GitHub](${GITHUB_SEARCH_URL})
"
TELEGRAM_MSG+="• [Web News](${WEB_SEARCH_URL})

"

TELEGRAM_MSG+="💡 Tip: Reply with 'search openclaw' for fresh results!"

# ============================================
# STEP 4: Send to Telegram
# ============================================
echo "📤 Sending to Telegram..." | tee -a "$LOG_FILE"

# Send via message tool (OpenClaw will handle routing)
echo "$TELEGRAM_MSG" > /tmp/openclaw_telegram_msg.txt

# ============================================
# STEP 5: Send Email Summary
# ============================================
echo "📧 Sending email summary..." | tee -a "$LOG_FILE"

# Create HTML email body
EMAIL_SUBJECT="🦀 OpenClaw Daily Briefing — $(date '+%B %d, %Y')"

EMAIL_HTML="<html>
<head>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px; }
h1 { color: #e74c3c; border-bottom: 2px solid #e74c3c; padding-bottom: 10px; }
h2 { color: #2c3e50; margin-top: 30px; }
.article { margin: 15px 0; padding: 15px; background: #f8f9fa; border-radius: 8px; }
.article-title { font-weight: bold; color: #2980b9; }
.article-meta { color: #7f8c8d; font-size: 0.9em; margin-top: 5px; }
.section { margin: 25px 0; }
.footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; color: #7f8c8d; font-size: 0.85em; }
a { color: #2980b9; }
.badge { display: inline-block; padding: 3px 8px; background: #e74c3c; color: white; border-radius: 12px; font-size: 0.75em; margin-left: 10px; }
</style>
</head>
<body>
<h1>🦀 OpenClaw Daily Briefing <span class=\"badge\">$(date '+%b %d')</span></h1>
<p>Your daily intelligence on OpenClaw, AI agents, and automation tools.</p>
"

# Add FreshRSS section
if [ -n "$FRESHRSS_MATCHES" ]; then
    EMAIL_HTML+="<div class=\"section\">
<h2>📰 FreshRSS Highlights</h2>
"
    
    # Parse and format FreshRSS output
    local count=0
    while IFS= read -r line && [ $count -lt 10 ]; do
        if [[ "$line" =~ ^\[(.*)\][[:space:]]+(.*)$ ]]; then
            local date="${BASH_REMATCH[1]}"
            local rest="${BASH_REMATCH[2]}"
            
            # Try to extract source and title
            if [[ "$rest" =~ ^([^:]+):[[:space:]]+(.*)$ ]]; then
                local source="${BASH_REMATCH[1]}"
                local title="${BASH_REMATCH[2]}"
                
                EMAIL_HTML+="<div class=\"article\">
<div class=\"article-title\">$title</div>
<div class=\"article-meta\">$source • $date</div>
</div>
"
                ((count++))
            fi
        fi
    done <<< "$FRESHRSS_MATCHES"
    
    EMAIL_HTML+="</div>
"
fi

# Add AI Agent news section
if [ -n "$FRESHRSS_AI" ]; then
    EMAIL_HTML+="<div class=\"section\">
<h2>🤖 Related: AI Agent News</h2>
"
    
    local count=0
    while IFS= read -r line && [ $count -lt 5 ]; do
        if [[ "$line" =~ ^\[(.*)\][[:space:]]+(.*)$ ]]; then
            local date="${BASH_REMATCH[1]}"
            local rest="${BASH_REMATCH[2]}"
            
            if [[ "$rest" =~ ^([^:]+):[[:space:]]+(.*)$ ]]; then
                local source="${BASH_REMATCH[1]}"
                local title="${BASH_REMATCH[2]}"
                
                EMAIL_HTML+="<div class=\"article\">
<div class=\"article-title\">$title</div>
<div class=\"article-meta\">$source • $date</div>
</div>
"
                ((count++))
            fi
        fi
    done <<< "$FRESHRSS_AI"
    
    EMAIL_HTML+="</div>
"
fi

# Add quick links
EMAIL_HTML+="<div class=\"section\">
<h2>🔍 Quick Searches</h2>
<ul>
<li><a href=\"$REDDIT_SEARCH_URL\">Reddit — OpenClaw posts (last 24h)</a></li>
<li><a href=\"$GITHUB_SEARCH_URL\">GitHub — OpenClaw repos (recently updated)</a></li>
<li><a href=\"$WEB_SEARCH_URL\">Web — OpenClaw AI agent news</a></li>
</ul>
</div>
"

EMAIL_HTML+="<div class=\"footer\">
<p>Generated by Krilly the Crab 🦀 at $(date '+%I:%M %p %Z')</p>
<p><em>Want to change these updates? Just ask!</em></p>
</div>
</body>
</html>"

# Save email HTML to file
echo "$EMAIL_HTML" > /tmp/openclaw_email.html

# Send email using SendClaw API
curl -s -X POST https://sendclaw.com/api/send \
    -H "Authorization: Bearer $SENDCLAW_API_KEY" \
    -H "Content-Type: application/json" \
    -d "{
        \"from\": \"$SENDCLAW_FROM\",
        \"to\": \"$USER_EMAIL\",
        \"subject\": \"$EMAIL_SUBJECT\",
        \"html\": $(cat /tmp/openclaw_email.html | jq -Rs .)
    }" >> "$LOG_FILE" 2>&1

echo "" | tee -a "$LOG_FILE"
echo "✅ Digest complete! Sent to Telegram and $USER_EMAIL" | tee -a "$LOG_FILE"
echo "=== End of Digest ===" | tee -a "$LOG_FILE"

exit 0
