#!/bin/bash
# One-time iGroup Email Cleanup Script
# Moves all remaining iGroup/MeetGeek emails to "1 A - Phill FastFlip Marketing Emails" folder
# Run this script once to clean up existing emails

echo "=== iGroup Email One-Time Cleanup ==="
echo "This script will move all iGroup/MeetGeek emails to the designated folder."
echo "Folder: '1 A - Phill FastFlip Marketing Emails' (Label_334090049224260461)"
echo ""

# Check if gmail-tool exists
if [ ! -f "/home/node/clawd/nova/gmail-tool" ]; then
    echo "❌ Error: gmail-tool not found at /home/node/clawd/nova/gmail-tool"
    exit 1
fi

cd /home/node/clawd

echo "Step 1: Checking seoservices account for iGroup emails..."
./nova/gmail-tool seoservices list --query "igroup OR yishan.tsai@igroup.tw OR meetgeek.ai" --max 100 > /tmp/igroup_emails.json

EMAIL_COUNT=$(python3 -c "import json, sys; data=json.load(open('/tmp/igroup_emails.json')); print(len(data))" 2>/dev/null || echo "0")

if [ "$EMAIL_COUNT" -eq "0" ]; then
    echo "✅ No iGroup emails found in seoservices account."
else
    echo "Found $EMAIL_COUNT iGroup emails in seoservices account."
    
    # Count emails not in folder
    NOT_IN_FOLDER=$(python3 -c "
import json, sys
data = json.load(open('/tmp/igroup_emails.json'))
count = 0
for email in data:
    labels = email.get('labels', [])
    if 'SENT' not in labels and 'Label_334090049224260461' not in labels:
        count += 1
print(count)
" 2>/dev/null || echo "0")
    
    echo "$NOT_IN_FOLDER emails need to be moved to iGroup folder."
    
    if [ "$NOT_IN_FOLDER" -gt "0" ]; then
        echo ""
        echo "Step 2: Moving emails to iGroup folder..."
        
        MOVED_COUNT=0
        for i in $(seq 0 $((EMAIL_COUNT-1))); do
            EMAIL_ID=$(python3 -c "
import json, sys
data = json.load(open('/tmp/igroup_emails.json'))
email = data[$i]
labels = email.get('labels', [])
if 'SENT' not in labels and 'Label_334090049224260461' not in labels:
    print(email.get('id', ''))
" 2>/dev/null)
            
            if [ -n "$EMAIL_ID" ]; then
                echo "Moving email $EMAIL_ID..."
                ./nova/gmail-tool seoservices add-label --id "$EMAIL_ID" --label "1 A - Phill FastFlip Marketing Emails"
                if [ $? -eq 0 ]; then
                    MOVED_COUNT=$((MOVED_COUNT + 1))
                    echo "✅ Moved successfully"
                else
                    echo "❌ Failed to move"
                fi
            fi
        done
        
        echo ""
        echo "✅ Successfully moved $MOVED_COUNT emails to iGroup folder!"
    else
        echo "✅ All iGroup emails are already in the correct folder!"
    fi
fi

echo ""
echo "=== Cleanup Complete ==="
echo "Daily automation will handle all new iGroup emails going forward."
echo "The Daily Email Cleanup job runs at 10:30 AM PHT every day."