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

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

# Manual refresh bypass — the epoch-float expiry breaks Credentials.from_authorized_user_file
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'},
)
try:
    with urllib.request.urlopen(req, timeout=15) as r:
        tok = json.loads(r.read())
except urllib.error.HTTPError as e:
    print("REFRESH FAILED", e.code, e.read().decode()[:300])
    sys.exit(1)

access_token = tok.get('access_token')
if not access_token:
    print("NO access_token in refresh response", tok)
    sys.exit(1)

H = {'Authorization': f'Bearer {access_token}'}

# Confirm identity
with urllib.request.urlopen(urllib.request.Request('https://gmail.googleapis.com/gmail/v1/users/me/profile', headers=H), timeout=15) as r:
    profile = json.loads(r.read())
print("ACCOUNT:", profile.get('emailAddress'))
print("TOTAL MESSAGES:", profile.get('messagesTotal'))

# Search Inbox for last 90 days, max 50, query = "David" near concrete/2631/Hornsby
epoch_90d = int(time.time()) - 90*24*3600
queries = [
    f'after:{epoch_90d} in:inbox (David concrete OR "2631" OR Hornsby)',
    f'after:{epoch_90d} in:sent (David concrete OR "2631" OR Hornsby)',
]

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

for q in queries:
    print("\n=== QUERY:", q)
    try:
        res = search(q)
    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[:30]:
        # Get full message
        u = f'https://gmail.googleapis.com/gmail/v1/users/me/messages/{m["id"]}?format=full'
        with urllib.request.urlopen(urllib.request.Request(u, headers=H), timeout=15) as r:
            full = json.loads(r.read())
        hdrs = {h['name']: h['value'] for h in full.get('payload', {}).get('headers', [])}
        frm = hdrs.get('From', '')
        subj = hdrs.get('Subject', '')
        date = hdrs.get('Date', '')
        snippet = full.get('snippet', '')[:200]
        print(f"\n[{date}] {frm}")
        print(f"  subj: {subj}")
        print(f"  snip: {snippet}")

# Persist refreshed token
data['access_token'] = access_token
if 'expires_in' in tok:
    data['expiry'] = time.time() + tok['expires_in']
with open(token_path, 'w') as f:
    json.dump(data, f, indent=2)
print("\nTOKEN refreshed and saved")