#!/bin/bash

# Sync mail from ProtonMail Bridge (suppress CLOSE error)
echo "Syncing mail from ProtonMail..."
mbsync -a 2>&1 | grep -v "CLOSE"

# Index new mail (this automatically runs post-new hook)
echo "Indexing new messages..."
notmuch new

# Move all deleted messages to Trash folder
echo "Cleaning up deleted messages..."
DELETED_COUNT=0
notmuch search --output=files tag:deleted 2>/dev/null | while read filepath; do
    if [ -f "$filepath" ]; then
        TRASH_DIR="$HOME/.local/share/mail/Trash/cur"
        mkdir -p "$TRASH_DIR"
        
        FILENAME=$(basename "$filepath")
        mv "$filepath" "$TRASH_DIR/$FILENAME"
        ((DELETED_COUNT++))
    fi
done

# Update notmuch after moving files
if [ $DELETED_COUNT -gt 0 ]; then
    echo "Moved $DELETED_COUNT message(s) to Trash"
    notmuch new --no-hooks >/dev/null 2>&1
fi

# Sync moved messages back to ProtonMail
echo "Syncing changes to ProtonMail..."
mbsync -a 2>&1 | grep -v "CLOSE" >/dev/null

# Notify if new mail
NEW=$(notmuch count tag:unread)
if [ $NEW -gt 0 ]; then
    notify-send "📬 Mail" "$NEW unread message(s)"
fi

echo "Sync complete: $(date)"
