import imaplib
import email
from email.header import decode_header

def check_gmail_for_leads(search_terms=None):
    """Check Gmail for responses from leads"""
    EMAIL = "jameyecho@gmail.com"
    APP_PASS = "lkbzsbavkvjnopqc"
    
    if search_terms is None:
        search_terms = ["fred", "whale", "sage", "security"]
    
    results = []
    try:
        mail = imaplib.IMAP4_SSL('imap.gmail.com')
        mail.login(EMAIL, APP_PASS)
        mail.select('INBOX')
        
        # Search last 7 days
        _, messages = mail.search(None, '(SINCE "01-Jan-2026")')
        msg_nums = messages[0].split()[-20:]  # Last 20 emails
        
        for num in msg_nums:
            _, msg_data = mail.fetch(num, '(RFC822)')
            msg = email.message_from_bytes(msg_data[0][1])
            
            subject = decode_header(msg["Subject"])[0][0]
            if isinstance(subject, bytes):
                subject = subject.decode()
            
            from_addr = msg["From"]
            date = msg["Date"]
            
            # Check if matches search terms
            text = f"{subject} {from_addr}".lower()
            if any(term.lower() in text for term in search_terms):
                results.append({
                    "from": from_addr,
                    "subject": subject,
                    "date": date
                })
        
        mail.logout()
    except Exception as e:
        return f"Error: {e}"
    
    return results

if __name__ == "__main__":
    matches = check_gmail_for_leads()
    print(f"Found {len(matches)} matching emails:")
    for m in matches:
        print(f"  From: {m['from']}")
        print(f"  Subject: {m['subject']}")
        print(f"  Date: {m['date']}")
        print()
