import json, datetime, sys
from pathlib import Path
from urllib.parse import urlencode
import urllib.request, urllib.error

TOKEN_PATH = Path.home() / '.hermes' / 'google_token.json'

def load(): return json.loads(TOKEN_PATH.read_text())
def save(t): TOKEN_PATH.write_text(json.dumps(t, indent=2)); TOKEN_PATH.chmod(0o600)

def api(url, tok):
    req = urllib.request.Request(url, headers={'Authorization': f'Bearer {tok}'})
    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]

def refresh(tok):
    form = urlencode({
        'client_id': tok['client_id'],
        'client_secret': tok['client_secret'],
        'refresh_token': tok['refresh_token'],
        'grant_type': 'refresh_token',
    }).encode()
    req = urllib.request.Request('https://oauth2.googleapis.com/token', data=form,
                                 headers={'Content-Type': 'application/x-www-form-urlencoded'})
    with urllib.request.urlopen(req, timeout=15) as r:
        resp = json.loads(r.read().decode())
    if 'access_token' not in resp:
        return None
    new = dict(tok)
    new['access_token'] = resp['access_token']
    new['token'] = resp['access_token']
    new['expiry'] = datetime.datetime.now(datetime.timezone.utc).timestamp() + resp.get('expires_in', 3600)
    new['expiry_date'] = int(datetime.datetime.now(datetime.timezone.utc).timestamp() * 1000) + resp.get('expires_in', 3600) * 1000
    if 'scope' in resp:
        new['scopes'] = resp['scope'].split(' ')
    return new

tok = load()
access = tok.get('access_token') or tok.get('token')

# Probe Gmail list first
url = 'https://gmail.googleapis.com/gmail/v1/users/me/messages?q=is:unread%20in:inbox&maxResults=15'
status, data = api(url, access)
print(f'GMAIL_PROBE status={status}')
if status == 401:
    print('REFRESHING...')
    new = refresh(tok)
    if not new:
        print('NEEDS_REAUTH')
        sys.exit(2)
    tok = new
    save(tok)
    access = tok['access_token']
    status, data = api(url, access)
    print(f'GMAIL_AFTER_REFRESH status={status}')
print('---')
print(json.dumps(data, indent=2)[:600])