#!/usr/bin/env python3
"""Check unread emails from Gmail. No external dependencies needed."""
import imaplib
import email
import os
import sys
from datetime import datetime, timedelta
from email.header import decode_header

def decode_subject(subject):
    """Decode email subject header."""
    if not subject:
        return "(no subject)"
    decoded = decode_header(subject)
    parts = []
    for part, charset in decoded:
        if isinstance(part, bytes):
            parts.append(part.decode(charset or 'utf-8', errors='replace'))
        else:
            parts.append(part)
    return ''.join(parts)

def check_email(hours=24, limit=15):
    pwd_file = os.path.expanduser('~/.openclaw/secrets/gmail-app-password.txt')
    pwd = open(pwd_file).read().strip()
    
    mail = imaplib.IMAP4_SSL('imap.gmail.com')
    mail.login('mikeziarko@gmail.com', pwd)
    mail.select('INBOX', readonly=True)
    
    since = (datetime.now() - timedelta(hours=hours)).strftime('%d-%b-%Y')
    status, data = mail.search(None, f'(UNSEEN SINCE {since})')
    ids = data[0].split()
    
    print(f"Unread: {len(ids)} emails in last {hours}h")
    print()
    
    for mid in ids[:limit]:
        _, msg_data = mail.fetch(mid, '(BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE)])')
        raw = msg_data[0][1].decode('utf-8', errors='replace')
        msg = email.message_from_string(raw)
        
        from_addr = msg.get('From', 'Unknown')
        subject = decode_subject(msg.get('Subject', ''))
        date = msg.get('Date', '')
        
        print(f"From: {from_addr}")
        print(f"Subject: {subject}")
        print(f"Date: {date}")
        print("---")
    
    if len(ids) > limit:
        print(f"... and {len(ids) - limit} more")
    
    mail.logout()

if __name__ == '__main__':
    hours = int(sys.argv[1]) if len(sys.argv) > 1 else 24
    limit = int(sys.argv[2]) if len(sys.argv) > 2 else 15
    check_email(hours, limit)
