import sys,json,time
from cdp import CDP
c=CDP('app.gamma.echosaw.com')
c.call('Network.enable')
c.call('Runtime.enable')
print('Network observation started',time.time(),flush=True)
pending=set()
while True:
    r=json.loads(c.w.recv()); m=r.get('method',''); p=r.get('params',{})
    if m=='Network.requestWillBeSent':
        q=p['request']; u=q['url']
        if any(s in u for s in ['/chat','rag','websocket','wss:']):
            print(json.dumps({'event':m,'id':p['requestId'],'method':q['method'],'url':u.split('?')[0],'time':time.time()}),flush=True)
    elif m=='Network.responseReceived':
        q=p['response'];u=q['url']
        if any(s in u for s in ['/chat','rag','websocket','wss:']):
            print(json.dumps({'event':m,'id':p['requestId'],'status':q['status'],'url':u.split('?')[0],'time':time.time()}),flush=True)
            if '/chat/status' in u:
                pending.add(p['requestId'])
    elif m=='Network.loadingFinished' and p['requestId'] in pending:
        body=c.call('Network.getResponseBody',{'requestId':p['requestId']})
        print(json.dumps({'event':'observedResponseBody','id':p['requestId'],'body':body,'time':time.time()}),flush=True)
        pending.remove(p['requestId'])
    elif m=='Network.loadingFailed':
        print(json.dumps({'event':m,'id':p['requestId'],'error':p.get('errorText'),'blockedReason':p.get('blockedReason'),'corsErrorStatus':p.get('corsErrorStatus'),'time':time.time()}),flush=True)
    elif m=='Runtime.exceptionThrown':
        print(json.dumps({'event':m,'text':p.get('exceptionDetails',{}).get('text'),'description':p.get('exceptionDetails',{}).get('exception',{}).get('description'),'time':time.time()}),flush=True)
