#!/usr/bin/env python3
"""Consolidated morning digest fetch — Sat 15 Aug 2026."""
import json, urllib.request, base64, re, html as htmllib
from datetime import datetime, timezone, timedelta

try:
    import zoneinfo
    SYD = zoneinfo.ZoneInfo('Australia/Sydney')
except Exception:
    SYD = timezone(timedelta(hours=10), name='AEST')

NOW = datetime.now(SYD)
WEEK_FROM = NOW + timedelta(days=7)
NOW_ISO = NOW.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
WEEK_ISO = WEEK_FROM.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')

tok = json.load(open('/root/.hermes/google_token.json'))
H = {'Authorization': f"Bearer {tok['access_token']}"}

def http_get(url, hdr=None, timeout=30):
    req = urllib.request.Request(url, headers=hdr or H)
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return r.status, r.read()

# --- Gmail: list top 50 unread, fetch metadata format=full ---
def fetch_msg(mid):
    rs, rb = http_get(f'https://gmail.googleapis.com/gmail/v1/users/me/messages/{mid}?format=full')
    return json.loads(rb) if rs == 200 else None

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

emails = []
status, rb = http_get('https://gmail.googleapis.com/gmail/v1/users/me/messages?q=is:unread&maxResults=50')
print(f"GMAIL LIST status={status}")
if status == 200:
    lst = json.loads(rb)
    for ref in lst.get('messages', []):
        full = fetch_msg(ref['id'])
        if not full:
            continue
        p = full.get('payload', {})
        emails.append({
            'id': ref['id'],
            'from': hdr(p.get('headers', []), 'From'),
            'subject': hdr(p.get('headers', []), 'Subject'),
            'date_header': hdr(p.get('headers', []), 'Date'),
            'internal_ms': full.get('internalDate'),
            'snippet': full.get('snippet', ''),
        })

# --- Calendar: next 7 days ---
events = []
cal_url = (
    'https://www.googleapis.com/calendar/v3/calendars/primary/events'
    f'?timeMin={NOW_ISO}&timeMax={WEEK_ISO}&singleEvents=true&orderBy=startTime&maxResults=50'
)
rs, rb = http_get(cal_url)
print(f"CALENDAR status={rs}")
if rs == 200:
    cal = json.loads(rb)
    for ev in cal.get('items', []):
        s = ev.get('start', {})
        e = ev.get('end', {})
        events.append({
            'summary': ev.get('summary', '(no title)'),
            'start': s.get('dateTime') or s.get('date'),
            'end': e.get('dateTime') or e.get('date'),
            'all_day': 'dateTime' not in s,
            'location': ev.get('location', ''),
            'attendees': len(ev.get('attendees', [])),
        })

out = {
    'fetched_at_syd': NOW.isoformat(),
    'now_syd': NOW.strftime('%A %d %b %Y %H:%M'),
    'emails': emails,
    'events': events,
}
json.dump(out, open('/tmp/morning_fetch.json', 'w'), indent=2)
print(f"WROTE emails={len(emails)} events={len(events)}")
