
import imaplib, email, os
from email.header import decode_header

creds = {}
with open('/opt/data/secrets/.huper-credentials') as f:
    for line in f:
        line = line.strip()
        if '=' in line and not line.startswith('#'):
            k, v = line.split('=', 1)
            creds[k.strip()] = v.strip()

m = imaplib.IMAP4_SSL(creds.get('IMAP_HOST', 'my.mailbux.com'), 993)
m.login(creds['HUPER_EMAIL'], creds['HUPER_PASSWORD'])
m.select('INBOX', readonly=True)

# Search for recent verification/code emails
_, data = m.search(None, '(SUBJECT "verification")')
ids = data[0].split()
print(f"Found {len(ids)} emails with 'verification' in subject")

# Get the last 5
for mid in ids[-5:]:
    _, msg_data = m.fetch(mid, '(BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE)])')
    for part in msg_data:
        if isinstance(part, tuple):
            headers = part[1].decode(errors='replace')
            print(f"--- ID {mid.decode()} ---")
            print(headers)
            print()

# Also search for Perplexity specifically
_, data = m.search(None, '(FROM "perplexity")')
ids = data[0].split()
print(f"Found {len(ids)} emails from Perplexity")

for mid in ids[-3:]:
    _, msg_data = m.fetch(mid, '(RFC822)')
    for part in msg_data:
        if isinstance(part, tuple):
            msg = email.message_from_bytes(part[1])
            subj = decode_header(msg['Subject'])[0][0]
            if isinstance(subj, bytes): subj = subj.decode()
            print(f"--- Perplexity email {mid.decode()} ---")
            print(f"From: {msg['From']}")
            print(f"Subject: {subj}")
            print(f"Date: {msg['Date']}")
            # Get body
            body_text = ""
            if msg.is_multipart():
                for p in msg.walk():
                    ct = p.get_content_type()
                    if ct == 'text/plain':
                        body = p.get_payload(decode=True)
                        if body:
                            body_text = body.decode(errors='replace')
                        break
                if not body_text:
                    for p in msg.walk():
                        ct = p.get_content_type()
                        if ct == 'text/html':
                            body = p.get_payload(decode=True)
                            if body:
                                body_text = body.decode(errors='replace')
                            break
            else:
                body = msg.get_payload(decode=True)
                if body:
                    body_text = body.decode(errors='replace')
            print(body_text[:1000])
            print()

m.logout()
