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

with open(os.path.expanduser('~/.openclaw/secrets/gmail-app-password.txt')) as f:
    password = f.read().strip()

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('mikeziarko@gmail.com', password)

all_ids = set()

for folder in ['inbox', '"[Gmail]/All Mail"', '"[Gmail]/Sent Mail"']:
    try:
        mail.select(folder)
        for search in ['FROM "ledger"', 'SUBJECT "ledger"', 'TEXT "ledgers online"', 'TEXT "jerby"']:
            _, msgs = mail.search(None, search)
            if msgs[0]:
                all_ids.update(msgs[0].split())
    except Exception as e:
        print(f"Folder {folder} error: {e}")

# Switch to All Mail for fetching
mail.select('"[Gmail]/All Mail"')

print(f"Found {len(all_ids)} emails total\n{'='*60}")

results = []
for mid in all_ids:
    try:
        _, data = mail.fetch(mid, '(RFC822)')
        msg = email.message_from_bytes(data[0][1])
        subject = decode_header(msg['Subject'])[0][0]
        if isinstance(subject, bytes):
            subject = subject.decode('utf-8', errors='replace')
        
        body = ''
        if msg.is_multipart():
            for part in msg.walk():
                if part.get_content_type() == 'text/plain':
                    body = part.get_payload(decode=True).decode('utf-8', errors='replace')
                    break
        else:
            body = msg.get_payload(decode=True)
            if isinstance(body, bytes):
                body = body.decode('utf-8', errors='replace')
        
        results.append({
            'from': msg['From'],
            'subject': subject,
            'date': msg['Date'],
            'body': body[:2000]
        })
    except Exception as e:
        print(f"Error fetching {mid}: {e}")

# Sort by date
results.sort(key=lambda x: x['date'] or '')

for r in results:
    print(f"\nFrom: {r['from']}")
    print(f"Subject: {r['subject']}")
    print(f"Date: {r['date']}")
    print(f"---")
    print(r['body'][:1500])
    print('='*60)

mail.logout()
