#!/usr/bin/env python3
"""Refresh Google OAuth token with embedded verify-write check (retired the
refresh-then-NameError bug from 2026-07-17 + 2026-08-08)."""
import json, time, urllib.request, urllib.error

TOKEN_PATH = '/root/.hermes/google_token.json'

with open(TOKEN_PATH) as f:
    tok = json.load(f)

# Compose refresh POST (x-www-form-urlencoded, no shell)
data = urllib.parse.urlencode({
    'client_id': tok['client_id'],
    'client_secret': tok['client_secret'],
    'refresh_token': tok['refresh_token'],
    'grant_type': 'refresh_token',
}).encode('ascii')

req = urllib.request.Request(
    tok['token_uri'],
    data=data,
    headers={'Content-Type': 'application/x-www-form-urlencoded'},
)

try:
    resp = urllib.request.urlopen(req, timeout=30)
    body = json.loads(resp.read())
except urllib.error.HTTPError as e:
    print(f'REFRESH_HTTP_FAIL: {e.code} {e.read().decode("utf-8", "replace")[:500]}')
    raise SystemExit(2)

if 'access_token' not in body:
    print(f'REFRESH_NO_TOKEN: {body}')
    raise SystemExit(3)

# Merge new fields — keep refresh_token (Google doesn't return it on refresh)
new = {**tok, **body}
# expiry_date = now + expires_in (ms)
new['expiry_date'] = int(time.time() * 1000) + int(body.get('expires_in', 3600)) * 1000

# Write atomically
import os
tmp_path = TOKEN_PATH + '.tmp'
with open(tmp_path, 'w') as f:
    json.dump(new, f, indent=2)
os.replace(tmp_path, TOKEN_PATH)

# EMBEDDED VERIFY-WRITE CHECK
saved = json.load(open(TOKEN_PATH))
if saved.get('access_token') != new['access_token']:
    print('WRITE_FAILED: token file not updated')
    raise SystemExit(4)
if 'expiry_date' in saved:
    delta_ms = saved['expiry_date'] - int(time.time() * 1000)
    if delta_ms < 0:
        print('WRITE_FAILED: expiry_date in past')
        raise SystemExit(5)
    print(f'REFRESH OK + VERIFIED, expires_in ~{delta_ms // 1000}s, delta={delta_ms//1000/3600:.2f}h')
else:
    print('REFRESH OK + VERIFIED (no expiry_date field)')
