import requests, io, sys, re
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
CID_OLD = 'jE5xt50qC7oIh1f32qMzA6hGznIU5mgH'
CID_PH  = 'QxeAC955IEDXBRcQGikSBAGXBUWKnstx'
TEN = 'vinfast-as-prod.jp.auth0.com'

def probe(cid, tag):
    url = (f'https://{TEN}/authorize?client_id={cid}'
           f'&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%2Fcallback&scope=openid%20profile%20email&state=p')
    r = requests.get(url, allow_redirects=False, timeout=15)
    txt = re.sub(r'<[^>]+>', ' ', r.text)
    txt = ' '.join(txt.split())[:150]
    loc = (r.headers.get('Location') or '')[:150]
    print(f'[{tag}] {r.status_code} | Location: {loc}')
    if r.status_code not in (302, 303):
        print(f'   body: {txt}')

probe(CID_OLD, 'authorize OLD-client')
probe(CID_PH, 'authorize PH-client (mồi réf 400 known)')

# giúp đăng nhập trên tenant MỚI bằng client CŨ: password + realm/conn variants
EMAIL, PW = 'minhhai113he@gmail.com', 'Minhgiang007?'
def tok(payload, tag):
    r = requests.post(f'https://{TEN}/oauth/token', json=payload, timeout=20)
    print(f'[{tag}] {r.status_code} {r.text[:150]}')
P = ('password', PW)
tok({'client_id': CID_OLD, 'grant_type': 'password', 'username': EMAIL, 'password': PW,
     'scope': 'openid profile email offline_access',
     'audience': 'https://mobile.ccar-asia.vinfastauto.com'}, 'JP+OLDclient aud-ccarasia')
tok({'client_id': CID_OLD, 'grant_type': 'password', 'username': EMAIL, 'password': PW,
     'scope': 'openid profile email offline_access',
     'audience': 'https://vinfast-as-prod.jp.auth0.com/api/v2/'}, 'JP+OLDclient aud-mgmt')
tok({'client_id': CID_OLD, 'grant_type': 'password', 'username': EMAIL, 'password': PW,
     'scope': 'openid profile email offline_access',
     'audience': 'https://vinfast-as-prod.jp.auth0.com/api/v2/',
     'realm': 'Username-Password-Authentication'}, 'JP+OLDclient aud-mgmt+realm')
# legacy dbconnections login
r = requests.post(f'https://{TEN}/dbconnections/login', data={
    'client_id': CID_OLD, 'username': EMAIL, 'password': PW,
    'connection': 'Username-Password-Authentication',
    'scope': 'openid profile email offline_access'}, timeout=20)
print('[dbconn JP+OLDclient]', r.status_code, r.text[:200])
