#!/usr/bin/env python3
"""Refresh Google OAuth token with verified write."""
import json, time, urllib.request, urllib.parse
from pathlib import Path

creds = json.load(open('/root/.hermes/google_client_secret.json'))['installed']
cid, csec, token_uri = creds['client_id'], creds['client_secret'], creds['token_uri']

tok = json.load(open('/root/.hermes/google_token.json'))
body = urllib.parse.urlencode({
    'client_id': cid, 'client_secret': csec,
    'refresh_token': tok['refresh_token'], 'grant_type': 'refresh_token',
}).encode()
req = urllib.request.Request(token_uri, data=body, method='POST',
                             headers={'Content-Type': 'application/x-www-form-urlencoded'})
with urllib.request.urlopen(req, timeout=30) as r:
    new = json.loads(r.read())

tok['access_token'] = new['access_token']
tok['expires_in'] = new.get('expires_in', 3600)
tok['expiry_date'] = int(time.time() * 1000) + new.get('expires_in', 3600) * 1000
Path('/root/.hermes/google_token.json').write_text(json.dumps(tok, indent=2))

saved = json.load(open('/root/.hermes/google_token.json'))
assert saved.get('access_token') == new['access_token'], 'WRITE FAILED'
delta_ms = saved['expiry_date'] - int(time.time() * 1000)
print(f"REFRESH OK, expires in ~{delta_ms/1000/3600:.2f}h, token={new['access_token'][:25]}...")
