#!/usr/bin/env python3
import imaplib
import email
from email.header import decode_header
from datetime import datetime, timedelta
import re

# Connect to Proton Bridge IMAP
imap_host = "127.0.0.1"
imap_port = 1143
username = "TonyOClaw1990@proton.me"
password = "Q3Y6w10Vx9BSnnnJQug0kQ"

print(f"Connecting to {imap_host}:{imap_port}...")
mail = imaplib.IMAP4(imap_host, imap_port)
mail.starttls()
mail.login(username, password)

# Select inbox
mail.select("INBOX")

# Search for all emails
status, messages = mail.search(None, "ALL")
email_ids = messages[0].split()

print(f"Found {len(email_ids)} emails in inbox\n")

# Track deletions
to_delete = []
two_weeks_ago = datetime.now() - timedelta(days=14)
one_week_ago = datetime.now() - timedelta(days=7)

def decode_str(s):
    if s is None:
        return ""
    if isinstance(s, bytes):
        s = s.decode('utf-8', errors='ignore')
    decoded = decode_header(s)
    result = []
    for content, encoding in decoded:
        if isinstance(content, bytes):
            result.append(content.decode(encoding or 'utf-8', errors='ignore'))
        else:
            result.append(content)
    return ''.join(result)

def should_delete(msg, msg_date):
    """Conservative deletion criteria"""
    subject = decode_str(msg.get("Subject", "")).lower()
    from_addr = decode_str(msg.get("From", "")).lower()
    
    # Test emails
    if "test" in subject and ("test" in from_addr or "openclaw" in from_addr):
        return True, "Test email"
    
    # Bounce notifications
    if "mail delivery failed" in subject or "returned mail" in subject or "undelivered" in subject:
        return True, "Bounce notification"
    
    # Old automated notifications (>2 weeks)
    if msg_date and msg_date < two_weeks_ago:
        automated_keywords = [
            "delivery confirmation", "order confirmation", "shipping notification",
            "automated", "no-reply", "noreply", "do not reply"
        ]
        if any(kw in subject or kw in from_addr for kw in automated_keywords):
            return True, f"Old automated notification ({msg_date.strftime('%Y-%m-%d')})"
    
    return False, None

# Review each email
for email_id in email_ids:
    status, msg_data = mail.fetch(email_id, "(RFC822)")
    
    for response_part in msg_data:
        if isinstance(response_part, tuple):
            msg = email.message_from_bytes(response_part[1])
            
            subject = decode_str(msg.get("Subject", ""))
            from_addr = decode_str(msg.get("From", ""))
            date_str = msg.get("Date", "")
            
            # Parse date
            msg_date = None
            try:
                msg_date = email.utils.parsedate_to_datetime(date_str)
                if msg_date.tzinfo is not None:
                    msg_date = msg_date.replace(tzinfo=None)
            except:
                pass
            
            # Check if should delete
            delete, reason = should_delete(msg, msg_date)
            
            if delete:
                age = ""
                if msg_date:
                    age = f" [{msg_date.strftime('%Y-%m-%d')}]"
                
                print(f"❌ DELETE: {subject[:60]}")
                print(f"   From: {from_addr[:60]}")
                print(f"   Reason: {reason}{age}\n")
                
                to_delete.append({
                    'id': email_id,
                    'subject': subject,
                    'from': from_addr,
                    'reason': reason,
                    'date': msg_date
                })
            else:
                age = ""
                if msg_date:
                    days_old = (datetime.now() - msg_date).days
                    age = f" [{days_old}d old]"
                
                print(f"✓ KEEP: {subject[:60]}{age}")

print(f"\n{'='*70}")
print(f"SUMMARY: {len(to_delete)} emails to delete out of {len(email_ids)} total")
print(f"{'='*70}\n")

# Delete marked emails
if to_delete:
    print("Deleting marked emails...")
    for item in to_delete:
        mail.store(item['id'], '+FLAGS', '\\Deleted')
        print(f"  Deleted: {item['subject'][:60]}")
    
    # Expunge to permanently delete
    mail.expunge()
    print(f"\n✓ Successfully deleted {len(to_delete)} emails")
else:
    print("No emails to delete")

# Logout
mail.close()
mail.logout()
print("\nDone!")
