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

def search_inbox(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()
    for search in ['FROM "ledger"', 'SUBJECT "ledger"', 'SUBJECT "invoice"']:
        try:
            _, msgs = mail.search(None, search)
            if msgs[0]:
                all_ids.update(msgs[0].split())
        except Exception as e:
            print(f"{label} search error: {e}")
    
    print(f"\n{label}: {len(all_ids)} emails found")
    
    results = []
    for mid in list(all_ids)[:20]:
        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':
                        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[:1500]
            })
        except Exception as e:
            print(f"Fetch error: {e}")
    
    mail.logout()
    return results

# Search personal Gmail
results = search_inbox(
    'mikeziarko@gmail.com',
    '~/.openclaw/secrets/gmail-app-password.txt',
    'mikeziarko@gmail.com'
)

# Search services inbox
results2 = search_inbox(
    'services@nomorechores.com',
    '~/.openclaw/secrets/gmail-services-app-password.txt',
    'services@nomorechores.com'
)

all_results = results + results2
all_results.sort(key=lambda x: x.get('date') or '')

print(f"\n{'='*60}")
print(f"TOTAL: {len(all_results)} emails")
print(f"{'='*60}")

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