import imaplib, email, json, sys

try:
    with open('/Eden/SECRETS/email_config.json') as f:
        config = json.load(f)
    
    mail = imaplib.IMAP4_SSL('imap.gmail.com')
    mail.login(config['user'], config['password'])
    mail.select('inbox')

    # Strict search for PayPal sender or explicit Receipt keywords
    print("🔎 Filtering for genuine PayPal receipts (Excluding PC Optimum)...")
    result, data = mail.search(None, '(OR FROM "service@paypal.com" TEXT "Payment received")')
    
    ids = data[0].split()
    if not ids:
        print("❌ No direct PayPal sender hits found. Searching text for '10,000' + 'PayPal'...")
        result, data = mail.search(None, '(AND TEXT "PayPal" TEXT "10,000")')
        ids = data[0].split()

    if not ids:
        print("❌ Still no hits. The email may be in the 'Spam' or 'Updates' folder.")
        sys.exit()

    print(f"✅ Found {len(ids)} filtered matches. Extracting...")
    
    for m_id in ids[-10:]: # Look at the last 10 to be safe
        _, msg_data = mail.fetch(m_id, '(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = email.message_from_bytes(response_part[1])
                # Filter out the PC Optimum garbage just in case
                if "pcoptimum" in str(msg['From']).lower():
                    continue
                print("\n" + "🎯 " + "="*40)
                print(f"DATE:    {msg['Date']}")
                print(f"FROM:    {msg['From']}")
                print(f"SUBJECT: {msg['Subject']}")
                print("="*42)
    
    mail.logout()
except Exception as e:
    print(f"❌ Error: {str(e)}")
