#!/usr/bin/env python3
import json, subprocess, datetime
from collections import Counter

raw = subprocess.check_output(
    ['docker','logs','grok2api','--since','2026-08-20T21:48:00','--until','2026-08-20T22:06:00'],
    stderr=subprocess.STDOUT, text=True, errors='replace')

c = Counter()
notable = []
u429 = Counter()
chat = []
for line in raw.splitlines():
    line = line.strip()
    if not line.startswith('{'):
        continue
    try:
        o = json.loads(line)
    except Exception:
        continue
    msg = o.get('msg','')
    path = o.get('path','')
    st = o.get('status')
    dur = o.get('duration_ms') or 0
    t = (o.get('time') or '')[:19]
    rid = o.get('request_id')
    if msg == 'http_request' and path in ('/v1/chat/completions','/v1/messages'):
        c['%s %s' % (path, st)] += 1
        start = '?'
        try:
            end = datetime.datetime.fromisoformat(o['time'][:26])
            start = (end - datetime.timedelta(milliseconds=dur)).strftime('%H:%M:%S')
        except Exception:
            pass
        rec = '%s start=%s %s st=%s dur=%sms rid=%s' % (t, start, path, st, dur, rid)
        chat.append(rec)
        if (st and st >= 400) or dur >= 80000:
            notable.append(rec)
    if msg == 'upstream_request_failed':
        c['upfail_%s' % o.get('status')] += 1
        code = o.get('upstream_code') or 'empty'
        u429[code] += 1
        if o.get('status') not in (429,):
            notable.append('%s upstream_fail st=%s acct=%s rid=%s code=%s' % (
                t, o.get('status'), o.get('account_id'), rid, code))
    if msg in ('request_canceled','client_disconnected','proxy_error'):
        notable.append('%s %s %s st=%s dur=%s rid=%s err=%s' % (
            t, msg, path, st, dur, rid, o.get('error')))

print('COUNTS')
for k,v in c.most_common():
    print(' ', k, v)
print('UPSTREAM_CODE')
for k,v in u429.most_common():
    print(' ', k, v)
print('NOTABLE')
for n in notable:
    print(' ', n)
print('ALL_CHAT_MSGS', len(chat))
for n in chat:
    print(' ', n)
