#!/usr/bin/env python3
import json, subprocess, sys, time
from curl_cffi import requests
BASE='https://gwde.baloise.de'
H={'X-Bug-Bounty':'dwbzn'}
principal=subprocess.check_output(['toadcli','cred','show','cred-1d4516f308d74b2d9b63a73243ee6899','-f','principal'],text=True).strip()
secret=subprocess.check_output(['toadcli','cred','show','cred-1d4516f308d74b2d9b63a73243ee6899','-f','secret'],text=True).strip()
s=requests.Session()
def rec(stage,r):
    out={'stage':stage,'status':r.status_code,'url':r.url,'exchange_id':getattr(r,'toadex_exchange_id',None),'location':r.headers.get('location'),'content_type':r.headers.get('content-type')}
    try:
        j=r.json(); out['json']=j
    except Exception:
        out['body']=r.text[:1000]
    print(json.dumps(out,ensure_ascii=False))
    return out
r=s.get(BASE+'/auth/ui/app',headers=H,allow_redirects=False,timeout=30); rec('init',r)
csrf=s.cookies.get('CSRFT759-S')
h={**H,'Accept':'application/json','Content-Type':'application/json','X-Same-Domain':'1'}
if csrf: h['X-CSRFT759']=csrf
r=s.post(BASE+'/auth/rest/public/authentication/applications/guidewire_pc/access',headers=h,data='null',allow_redirects=False,timeout=30); rec('select_guidewire_pc',r)
time.sleep(1)
# Refresh token in case gateway rotated it.
csrf=s.cookies.get('CSRFT759-S')
if csrf: h['X-CSRFT759']=csrf
h['X-Continue-Flow']='true'
r=s.post(BASE+'/auth/rest/public/authentication/password/check',headers=h,json={'username':principal,'password':secret},allow_redirects=False,timeout=30); auth=rec('password_check',r)
# Do not retry any credential variant. Read flow and app boundary only.
csrf=s.cookies.get('CSRFT759-S')
if csrf: h['X-CSRFT759']=csrf
r=s.get(BASE+'/auth/rest/public/flow',headers=h,allow_redirects=False,timeout=30); rec('flow_after',r)
r=s.get(BASE+'/pc/',headers=H,allow_redirects=False,timeout=30); rec('pc_after',r)
