#!/usr/bin/env python3
"""
Fetch inbox emails from both accounts, filter out newsletters/promos,
return everything that looks like real human mail or action items.
"""
import json, os, re, urllib.parse, urllib.request, base64

WORKSPACE = os.environ.get('WORKSPACE', '/root/.openclaw/workspace')
GOOGLE_AUTH_DIR = os.path.join(WORKSPACE, 'google-auth')

ACCOUNTS = [
    {'label': 'kitt@curiousendeavor.com', 'token': 'token.json'},
    {'label': 'assafdagancos@gmail.com', 'token': 'token-personal.json'},
]

SKIP_SENDERS = [
    'noreply', 'no-reply', 'donotreply', 'notifications@', 'mailer@',
    'newsletter', 'updates@', 'hello@', 'info@skool', 'system@',
    'drive-shares-noreply', 'security-noreply', 'accounts-noreply',
    'linkedin.com', 'twitter.com', 'facebook.com', 'instagram.com',
    'github.com', 'vercel.com', 'stripe.com', 'paypal.com',
]

def refresh_token(token_path):
    with open(token_path) as f:
        d = json.load(f)
    data = urllib.parse.urlencode({
        'client_id': d['client_id'],
        'client_secret': d['client_secret'],
        'refresh_token': d['refresh_token'],
        'grant_type': 'refresh_token',
    }).encode()
    req = urllib.request.Request('https://oauth2.googleapis.com/token', data=data)
    resp = urllib.request.urlopen(req)
    return json.loads(resp.read())['access_token']

def gmail_get(token, path):
    url = f'https://gmail.googleapis.com/gmail/v1{path}'
    req = urllib.request.Request(url, headers={'Authorization': f'Bearer {token}'})
    raw = urllib.request.urlopen(req).read()
    return json.loads(raw)

def get_header(headers, name):
    for h in headers:
        if h['name'].lower() == name.lower():
            return h['value']
    return ''

def is_human(sender, subject):
    s = sender.lower()
    for skip in SKIP_SENDERS:
        if skip in s:
            return False
    # Skip obvious automated subjects
    auto_subjects = ['unsubscribe', 'confirm your', 'verify your', 'receipt', 'invoice #',
                     'your order', 'shipment', 'delivery', 'subscription', 'trial']
    subj_lower = subject.lower()
    for a in auto_subjects:
        if a in subj_lower:
            return False
    return True

def fetch_emails(account):
    token_path = os.path.join(GOOGLE_AUTH_DIR, account['token'])
    if not os.path.exists(token_path):
        return []
    try:
        token = refresh_token(token_path)
    except Exception as e:
        return [{'error': str(e)}]

    results = []
    # Fetch from INBOX only, all unread + recent read (last 50)
    params = urllib.parse.urlencode({
        'labelIds': 'INBOX',
        'maxResults': 50,
        'q': 'in:inbox',
    })
    data = gmail_get(token, f'/users/me/messages?{params}')
    msgs = data.get('messages', [])

    for m in msgs:
        try:
            detail = gmail_get(token, f'/users/me/messages/{m["id"]}?format=metadata&metadataHeaders=From&metadataHeaders=Subject&metadataHeaders=Date')
            headers = detail.get('payload', {}).get('headers', [])
            sender = get_header(headers, 'From')
            subject = get_header(headers, 'Subject')
            date = get_header(headers, 'Date')
            snippet = detail.get('snippet', '')
            labels = detail.get('labelIds', [])
            unread = 'UNREAD' in labels

            results.append({
                'id': m['id'],
                'sender': sender,
                'subject': subject,
                'date': date,
                'snippet': snippet[:200],
                'unread': unread,
                'labels': labels,
                'human': is_human(sender, subject),
            })
        except:
            continue

    return results

def main():
    output = {}
    for account in ACCOUNTS:
        emails = fetch_emails(account)
        output[account['label']] = emails

    print(json.dumps(output, indent=2, ensure_ascii=False))

if __name__ == '__main__':
    main()
