# -*- coding: utf-8 -*-
# Quét các grant_type được phép trên /ccaruaa/oauth/token (client CAPP + secret mới)
import requests, base64, io, sys, json, uuid, time
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

EMAIL = "minhhai113he@gmail.com"
PASSWORD = "Minhgiang007?"
BASE = "https://mobile.connected-car.vinfast.vn"
AUTH0 = "https://vin3s.au.auth0.com/oauth/token"
AUTH0_CLIENT = "jE5xt50qC7oIh1f32qMzA6hGznIU5mgH"
CLIENT_ID = "capp8OXWD9bFbGiFG"
SECRET_NEW = "bqFgjKCB6SJjgL7m"
CRED = base64.b64encode(f"{CLIENT_ID}:{SECRET_NEW}".encode()).decode()

# Lấy Auth0 token RS256 (audience)
r = requests.post(AUTH0, json={
    "client_id": AUTH0_CLIENT, "grant_type": "password",
    "username": EMAIL, "password": PASSWORD,
    "audience": "https://mobile.connected-car.vinfast.vn",
    "scope": "openid profile email offline_access"}, timeout=20)
a0tok = r.json().get("access_token", "")
a0ref = r.json().get("refresh_token", "")
print("Auth0 token:", len(a0tok), "ch | refresh:", bool(a0ref))

def app_headers():
    dev = str(uuid.uuid4()).upper()
    return {
        "Authorization": f"Basic {CRED}",
        "Content-Type": "application/x-www-form-urlencoded",
        "user-agent": f"iOS - {dev} - 2.26.11",
        "x-service-name": "CAPP", "x-app-version": "2.26.11",
        "x-device-identifier": dev, "x-device-family": "iPhone 15 Pro",
        "x-device-platform": "iPhone15Pro", "x-device-locale": "vi_VN",
        "x-device-os-version": "27.0.1", "x-timezone": "Asia/Ho_Chi_Minh",
        "x-player-identifier": EMAIL,
    }

GRANTS = [
    ("jwt-bearer (assertion=Auth0 tok)", {"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": a0tok}),
    ("token-exchange (subject_token)", {"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
                                        "subject_token": a0tok, "subject_token_type": "urn:ietf:params:oauth:token-type:access_token"}),
    ("jwt-bearer realm", {"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": a0tok, "realm": "vin3s.au.auth0.com"}),
    ("authorization_code dummy", {"grant_type": "authorization_code", "code": "dummy"}),
    ("device_code", {"grant_type": "urn:ietf:params:oauth:grant-type:device_code", "device_code": "dummy"}),
    ("client_credentials", {"grant_type": "client_credentials"}),
]

for name, body in GRANTS:
    try:
        r = requests.post(f"{BASE}/ccaruaa/oauth/token", headers=app_headers(), data=body, timeout=20)
        print(f"[{r.status_code}] {name}: {(r.text or '')[:220]}")
    except Exception as e:
        print(f"[EXC] {name}: {e}")
