#!/usr/bin/env python3
"""Fetch snippets for top-5 selection."""
import json, urllib.request, urllib.error, html
from pathlib import Path

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

ids = [
    '19f710bd1831852c',  # not yet — replace with actual
]

# Read the actual ID list from the prior run's logs (re-fetch via list)
list_url = 'https://gmail.googleapis.com/gmail/v1/users/me/messages?q=is:unread%20in:inbox&maxResults=20'
req = urllib.request.Request(list_url, headers={'Authorization': f'Bearer {access}'})
with urllib.request.urlopen(req, timeout=15) as r:
    data = json.loads(r.read().decode())

# Sort and pick top 5 most recent job-relevant (skip CATEGORY_PROMOTIONS)
all_msgs = []
for m in data.get('messages', []):
    mid = m['id']
    url = f'https://gmail.googleapis.com/gmail/v1/users/me/messages/{mid}'
    req2 = urllib.request.Request(url, headers={'Authorization': f'Bearer {access}'})
    with urllib.request.urlopen(req2, timeout=15) as r2:
        md = json.loads(r2.read().decode())
    hdrs_list = (md.get('payload') or {}).get('headers') or []
    hdrs = {h['name']: html.unescape(h['value']) for h in hdrs_list}
    internal = int(md.get('internalDate', 0)) / 1000.0
    all_msgs.append({
        'id': mid,
        'from': hdrs.get('From', ''),
        'subject': hdrs.get('Subject', ''),
        'snippet': (md.get('snippet') or '')[:160],
        'ts': internal,
        'labels': md.get('labelIds', []),
    })

all_msgs.sort(key=lambda x: x['ts'], reverse=True)
job_relevant = [m for m in all_msgs if 'CATEGORY_PROMOTIONS' not in m['labels'] and 'CATEGORY_SOCIAL' not in m['labels']]
print(f'TOTAL={len(all_msgs)} JOB={len(job_relevant)}')

print('\n=== TOP 5 JOB-RELEVANT (newest first) ===')
for i, m in enumerate(job_relevant[:5], 1):
    when = __import__('datetime').datetime.fromtimestamp(m['ts'], tz=__import__('zoneinfo').ZoneInfo('Australia/Sydney')).strftime('%a %d %b %H:%M')
    print(f'\n[{i}] {when}')
    print(f'FROM: {m["from"]}')
    print(f'SUBJ: {m["subject"]}')
    print(f'SNIP: {m["snippet"]}')
    print(f'LABELS: {",".join(m["labels"])}')