#!/usr/bin/env python3
"""Dive into the most recent unread emails to surface the real top 5."""
import json, urllib.request, urllib.error, base64, re, html as htmllib

TOKEN_PATH = '/root/.hermes/google_token.json'
tok = json.load(open(TOKEN_PATH))
access = tok['access_token']

def api_get(url, params=None):
    if params:
        url = url + '?' + urllib.parse.urlencode(params)
    req = urllib.request.Request(url, headers={'Authorization': f'Bearer {access}'})
    return json.loads(urllib.request.urlopen(req, timeout=30).read())

def extract_body_text(payload):
    if payload.get('body', {}).get('data'):
        raw = payload['body']['data']; padded = raw + '=' * (-len(raw) % 4)
        return base64.urlsafe_b64decode(padded).decode('utf-8', 'replace')
    for p in payload.get('parts', []):
        if p.get('mimeType') == 'text/plain':
            raw = p.get('body', {}).get('data', '')
            if raw:
                padded = raw + '=' * (-len(raw) % 4)
                return base64.urlsafe_b64decode(padded).decode('utf-8', 'replace')
    for p in payload.get('parts', []):
        t = extract_body_text(p)
        if t: return t
    return ''

def extract_body_html(payload):
    if payload.get('mimeType') == 'text/html' and payload.get('body', {}).get('data'):
        raw = payload['body']['data']; padded = raw + '=' * (-len(raw) % 4)
        return base64.urlsafe_b64decode(padded).decode('utf-8', 'replace')
    for p in payload.get('parts', []):
        t = extract_body_html(p)
        if t: return t
    return ''

def html_to_text(html):
    text = re.sub(r'<style[^>]*>.*?</style>', '', html, flags=re.S | re.I)
    text = re.sub(r'<[^>]+>', ' ', text)
    text = html.unescape(text)
    text = re.sub(r'\s+', ' ', text)
    return text.strip()

list_url = 'https://gmail.googleapis.com/gmail/v1/users/me/messages'
listing = api_get(list_url, {'q': 'is:unread in:inbox', 'maxResults': '50'})
msgs = listing.get('messages', [])

# Pull everything by date desc
emails = []
for m in msgs:
    full = api_get(f"{list_url}/{m['id']}", {'format': 'full'})
    h = {x['name'].lower(): x['value'] for x in full.get('payload', {}).get('headers', [])}
    body = extract_body_text(full.get('payload', {})) or html_to_text(extract_body_html(full.get('payload', {})))
    emails.append({
        'subject': h.get('subject',''),
        'from': h.get('from',''),
        'date': h.get('date',''),
        'snippet': full.get('snippet',''),
        'body': body[:2500],
    })

emails.sort(key=lambda e: e['date'], reverse=True)

# Targets
TARGETS = [
    'Wentworth Point',
    'Bennelong',
    'Bellevue',
    'P234',
    'P252',
    'Nutrisoy',
    'East and North Footpath',
    'TCE Granville',
    'Parklife',
    'Town Hall',
    'Skylight',
    'Lighthorse',
    'TCE Contracting',
    'Little Bay',
    'Brand Assets',
    'Remobilisation',
    'Remote',
    'LED Strip',
    'Timesheet',
    'parking',
]
for t in TARGETS:
    print(f"\n=== {t} ===")
    for e in emails:
        if t.lower() in e['subject'].lower() or t.lower() in e['from'].lower():
            print(f"  {e['date'][:25]} | {e['from'][:40]} | {e['subject'][:60]}")
            if e['body']:
                print(f"  body: {e['body'][:600]}")
