# -*- coding: utf-8 -*-
# Test Cognito pool với Auth0 RS256 token ĐÚNG AUDIENCE (như app thật)
import requests, io, sys, json, time
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

EMAIL = "minhhai113he@gmail.com"
PASSWORD = "Minhgiang007?"
AUTH0 = "https://vin3s.au.auth0.com/oauth/token"
AUTH0_CLIENT = "jE5xt50qC7oIh1f32qMzA6hGznIU5mgH"
POOL = "ap-southeast-1:c6537cdf-92dd-4b1f-99a8-9826f153142a"
REGION = "ap-southeast-1"
AUTH0_DOMAIN = "vin3s.au.auth0.com"

# 1) Auth0 token ĐÚNG như app (audience + scope y hệt HAR)
r = requests.post(AUTH0, json={
    "client_id": AUTH0_CLIENT, "grant_type": "password",
    "username": EMAIL, "password": PASSWORD,
    "audience": "https://mobile.connected-car.vinfast.vn",
    "scope": "offline_access openid profile email read:current_user_metadata"}, timeout=20)
a0 = r.json()
tok = a0.get("access_token", "")
print("Auth0 token:", len(tok), "ch, header:", tok.split('.')[0][:60])

hdr = {"Content-Type": "application/x-amz-json-1.1", "X-Amz-Target": "AWSCognitoIdentityService.GetId"}
print("\n== Cognito GetId với Logins map ==", AUTH0_DOMAIN)
r1 = requests.post(f"https://cognito-identity.{REGION}.amazonaws.com/", headers=hdr,
                   json={"IdentityPoolId": POOL, "Logins": {AUTH0_DOMAIN: tok}}, timeout=20)
print("status:", r1.status_code, "body:", (r1.text or "")[:400])

if r1.status_code == 200:
    identity_id = r1.json()["IdentityId"]
    hdr2 = {"Content-Type": "application/x-amz-json-1.1", "X-Amz-Target": "AWSCognitoIdentityService.GetCredentialsForIdentity"}
    r2 = requests.post(f"https://cognito-identity.{REGION}.amazonaws.com/", headers=hdr2,
                       json={"IdentityId": identity_id, "Logins": {AUTH0_DOMAIN: tok}}, timeout=20)
    print("GetCredentials status:", r2.status_code)
    j = r2.json()
    if "Credentials" in j:
        c = j["Credentials"]
        print("  AccessKeyId:", c["AccessKeyId"][:20])
        print("  ✅✅ COGNITO NHẬN AUTH0 TOKEN RS256!!!")
    else:
        print("  body:", r2.text[:300])
