import json, urllib.request, urllib.parse, urllib.error, sys, time, re

token_path = '/root/.hermes/google_token.json'
with open(token_path) as f:
    data = json.load(f)

# Refresh token
req = urllib.request.Request(
    'https://oauth2.googleapis.com/token',
    data=urllib.parse.urlencode({
        'client_id': data['client_id'],
        'client_secret': data['client_secret'],
        'refresh_token': data['refresh_token'],
        'grant_type': 'refresh_token',
    }).encode(),
    headers={'Content-Type': 'application/x-www-form-urlencoded'},
)
with urllib.request.urlopen(req, timeout=15) as r:
    tok = json.loads(r.read())
access_token = tok['access_token']
H = {'Authorization': f'Bearer {access_token}'}
data['access_token'] = access_token
data['expiry'] = time.time() + tok.get('expires_in', 3600)
with open(token_path, 'w') as f:
    json.dump(data, f, indent=2)

def search(q, max_results=50):
    url = 'https://gmail.googleapis.com/gmail/v1/users/me/messages?' + urllib.parse.urlencode({
        'q': q, 'maxResults': str(max_results),
    })
    with urllib.request.urlopen(urllib.request.Request(url, headers=H), timeout=20) as r:
        return json.loads(r.read())

def fetch(mid):
    u = f'https://gmail.googleapis.com/gmail/v1/users/me/messages/{mid}?format=full'
    with urllib.request.urlopen(urllib.request.Request(u, headers=H), timeout=15) as r:
        return json.loads(r.read())

def show(full):
    hdrs = {h['name']: h['value'] for h in full.get('payload', {}).get('headers', [])}
    return {
        'from': hdrs.get('From', ''),
        'to': hdrs.get('To', ''),
        'cc': hdrs.get('Cc', ''),
        'subj': hdrs.get('Subject', ''),
        'date': hdrs.get('Date', ''),
        'snippet': full.get('snippet', '')[:300],
    }

epoch_180d = int(time.time()) - 180*24*3600

queries = [
    f'after:{epoch_180d} (concrete order OR "concrete delivery" OR docket OR Boral OR Hanson OR "concrete supply") (Hornsby OR "2631" OR "01-2275" OR walkway OR "edge beam" OR "footpath")',
    f'after:{epoch_180d} (Joel Hornsby OR Joel Solutions+ OR Joel foreman)',
    f'after:{epoch_180d} in:any (concrete delivery docket) Hornsby',
]

seen = set()
for q in queries:
    print("\n=== QUERY:", q[:120])
    try:
        res = search(q, 50)
    except urllib.error.HTTPError as e:
        print("SEARCH FAILED", e.code, e.read().decode()[:300])
        continue
    msgs = res.get('messages', [])
    print("hits:", len(msgs))
    for m in msgs:
        if m['id'] in seen:
            continue
        seen.add(m['id'])
        full = fetch(m['id'])
        info = show(full)
        print(f"\n[{info['date']}] {info['from']}")
        if info['to']:
            print(f"  to: {info['to']}")
        print(f"  subj: {info['subj']}")
        print(f"  snip: {info['snippet']}")