#!/bin/bash
# Check Krilly's AgentMail inbox and alert Anthony of new emails
# SILENT MODE: Only outputs anything if there are new emails to report

set -e

INBOX="krilly@agentmail.to"
API_KEY="am_us_22a6a04a84144467993d5b90be8bbd5d1482ca615a4e17561682dd3d6831f932"
LAST_CHECK_FILE="/tmp/krilly-last-email-check"

# Get current timestamp
CURRENT_TIME=$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")

# Get last check time (default to 1 hour ago if file doesn't exist)
if [[ -f "$LAST_CHECK_FILE" ]]; then
    LAST_CHECK=$(cat "$LAST_CHECK_FILE")
else
    LAST_CHECK=$(date -u -d '1 hour ago' +"%Y-%m-%dT%H:%M:%S.000Z")
fi

# Get messages since last check
MESSAGES=$(curl -s -H "Authorization: Bearer $API_KEY" \
    "https://api.agentmail.to/v0/inboxes/$INBOX/messages?limit=20&after=$LAST_CHECK")

# Simple check for new messages (look for messages without "sent" label)
if echo "$MESSAGES" | grep -q '"messages":\s*\[\s*\]'; then
    NEW_COUNT=0
elif echo "$MESSAGES" | grep -v '"sent"' | grep -q '"message_id"'; then
    NEW_COUNT=$(echo "$MESSAGES" | grep -o '"message_id"' | grep -v -A5 -B5 '"sent"' | wc -l)
    if [[ "$NEW_COUNT" -lt 1 ]]; then
        NEW_COUNT=1  # At least one if we found messages
    fi
else
    NEW_COUNT=0
fi

# SILENT: Only output and notify if there are new emails
if [[ "$NEW_COUNT" -gt 0 ]]; then
    # Send Telegram notification
    MESSAGE="🦀 **Krilly received $NEW_COUNT new email(s)!**

📧 Check full inbox: https://sendclaw.com/dashboard"

    /home/openclaw/.npm-global/bin/openclaw message send \
        --channel telegram \
        --target "telegram:1793951355" \
        --message "$MESSAGE" 2>/dev/null || true
fi

# Always update last check time (silently)
echo "$CURRENT_TIME" > "$LAST_CHECK_FILE"