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

def search_all(email_addr, password_file, label):
    with open(os.path.expanduser(password_file)) as f:
        password = f.read().strip()

    mail = imaplib.IMAP4_SSL('imap.gmail.com')
    mail.login(email_addr, password)
    mail.select('inbox')
    
    all_ids = set()
    # Cast wider net
    searches = [
        'FROM "ledger"',
        'FROM "jerby"',
        'FROM "bookkeeper"',
        'FROM "livia"',
        'SUBJECT "bookkeeping"',
        'SUBJECT "invoice" FROM "ledger"',
    ]
    for search in searches:
        try:
            _, msgs = mail.search(None, search)
            if msgs[0]:
                ids = msgs[0].split()
                all_ids.update(ids)
                print(f"  {label} '{search}': {len(ids)} hits")
        except Exception as e:
            print(f"  {label} search '{search}' error: {e}")
    
    results = []
    for mid in list(all_ids)[:30]:
        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():
                    ct = part.get_content_type()
                    if ct == 'text/plain':
                        raw = part.get_payload(decode=True)
                        if raw:
                            body = raw.decode('utf-8', errors='replace')
                        break
            else:
                raw = msg.get_payload(decode=True)
                if raw:
                    body = raw.decode('utf-8', errors='replace')
                elif isinstance(msg.get_payload(), str):
                    body = msg.get_payload()
            
            results.append({
                'from': msg['From'],
                'subject': subject,
                'date': msg['Date'],
                'body': body
            })
        except Exception as e:
            print(f"  Fetch error: {e}")
    
    mail.logout()
    return results

print("Searching mikeziarko@gmail.com...")
r1 = search_all('mikeziarko@gmail.com', '~/.openclaw/secrets/gmail-app-password.txt', 'gmail')

print("\nSearching services@nomorechores.com...")
r2 = search_all('services@nomorechores.com', '~/.openclaw/secrets/gmail-services-app-password.txt', 'services')

all_r = r1 + r2
all_r.sort(key=lambda x: x.get('date') or '')

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