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

t = json.loads(Path('/root/.hermes/google_token.json').read_text())
access = t.get('access_token') or t.get('token')

sent_ids = json.loads(Path('/tmp/g_sent_ids.json').read_text())

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]

stale = []
now_ms = int(datetime.datetime.now(datetime.timezone.utc).timestamp() * 1000)
cutoff_ms = now_ms - (3 * 24 * 3600 * 1000)  # 3 days

for mid in sent_ids:
    s, d = api(
        f'https://gmail.googleapis.com/gmail/v1/users/me/messages/{mid}?format=full', access,
    )
    if s != 200:
        continue
    headers = {h['name']: h['value'] for h in d.get('payload', {}).get('headers', [])}
    thread_id = d.get('threadId')
    sent_ts = int(d.get('internalDate', 0))
    subj = headers.get('Subject', '')
    frm = headers.get('From', '')

    # Fetch the thread to check for replies after sent_ts
    st, td = api(
        f'https://gmail.googleapis.com/gmail/v1/users/me/threads/{thread_id}?format=metadata&metadataHeaders=From&metadataHeaders=Date', access,
    )
    if st != 200:
        continue
    replies = []
    for m in td.get('messages', []):
        m_ts = int(m.get('internalDate', 0))
        m_id = m.get('id')
        m_headers = {h['name']: h['value'] for h in m.get('payload', {}).get('headers', [])}
        m_from = m_headers.get('From', '')
        # Skip self / sent
        if m_id == mid:
            continue
        if 'lfcs.com.au' in m_from.lower():
            continue
        if m_ts > sent_ts:
            replies.append((m_ts, m_from, m_headers.get('Subject', '')))
    if not replies and sent_ts < cutoff_ms:
        # Stale outbound (older than 3 days, no reply from non-LFCS)
        stale.append({
            'subject': subj,
            'to': frm,
            'sent_date': headers.get('Date', ''),
            'sent_ms': sent_ts,
        })

stale.sort(key=lambda x: x['sent_ms'])
Path('/tmp/g_stale.json').write_text(json.dumps(stale, indent=2))
print(f'STALE_FOUND={len(stale)}')
for s in stale:
    print(f"  - {s['sent_date']}  {s['to'][:50]}  {s['subject'][:80]}")
