import json, urllib.request, datetime
from pathlib import Path

TOKEN_PATH = Path.home() / '.hermes' / 'google_token.json'
t = json.loads(TOKEN_PATH.read_text())
access = t['access_token']

def api(url):
    req = urllib.request.Request(url, headers={'Authorization': f'Bearer {access}'})
    try:
        with urllib.request.urlopen(req, timeout=15) as r:
            return r.status, json.loads(r.read().decode())
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode()[:300]

# Gmail: unread inbox
s, data = api('https://gmail.googleapis.com/gmail/v1/users/me/messages?q=is:unread%20in:inbox%20-category:promotions%20-category:social&maxResults=15')
print('GMAIL', s)
if s != 200:
    print(json.dumps(data)[:500])
    raise SystemExit(1)

ids = [m['id'] for m in data.get('messages', [])]
print('unread_count:', len(ids))
print('ids:', ids[:15])

# Calendar: next 7 days UTC
now = datetime.datetime.now(datetime.timezone.utc)
end = now + datetime.timedelta(days=7)
time_min = now.strftime('%Y-%m-%dT%H:%M:%SZ')
time_max = end.strftime('%Y-%m-%dT%H:%M:%SZ')

s, data = api(f'https://www.googleapis.com/calendar/v3/calendars/primary/events?timeMin={time_min}&timeMax={time_max}&singleEvents=true&orderBy=startTime&maxResults=30')
print('CAL', s)
if s != 200:
    print(json.dumps(data)[:500])
else:
    items = data.get('items', [])
    print('cal_events:', len(items))
    for ev in items:
        start = ev.get('start', {}).get('dateTime') or ev.get('start', {}).get('date')
        print(' -', start, '|', ev.get('summary', '(no title)'), '|', ev.get('location', ''))

# Save IDs and event list for fanout step
Path('/tmp/g_ids.json').write_text(json.dumps(ids))
