# -*- coding: utf-8 -*-
# Khai thác tiếp: grant_type nào được phép + nhóm endpoint /auth0/account/* có nhận Auth0 token?
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()

def app_headers(dev=None):
    dev = dev or str(uuid.uuid4()).upper()
    return {
        "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,
    }

print("=" * 70)
print("1) grant_type=app KHÔNG signature -> server báo gì?")
h = app_headers(); h["Authorization"] = f"Basic {CRED}"
h["Content-Type"] = "application/x-www-form-urlencoded"
r = requests.post(f"{BASE}/ccaruaa/oauth/token", headers=h,
                  data={"grant_type": "app", "username": EMAIL,
                        "clientInstanceId": str(uuid.uuid4()),
                        "timestamp": str(int(time.time() * 1000))}, timeout=20)
print("   status:", r.status_code, "body:", (r.text or "")[:300])

print("=" * 70)
print("2) Đăng nhập Auth0 (password grant) -> Auth0 token")
r = requests.post(AUTH0, json={
    "client_id": AUTH0_CLIENT, "grant_type": "password",
    "username": EMAIL, "password": PASSWORD,
    "scope": "openid profile email offline_access"}, timeout=20)
print("   status:", r.status_code)
a0 = r.json() if r.status_code == 200 else {}
a0_tok = a0.get("access_token", "")
a0_refresh = a0.get("refresh_token", "")
print("   access_token:", a0_tok[:40], f"({len(a0_tok)}ch)", "| refresh:", bool(a0_refresh))

print("=" * 70)
print("3) grant_type=refresh_token trên /ccaruaa (dùng Auth0 refresh token)")
h = app_headers(); h["Authorization"] = f"Basic {CRED}"
h["Content-Type"] = "application/x-www-form-urlencoded"
if a0_refresh:
    r = requests.post(f"{BASE}/ccaruaa/oauth/token", headers=h,
                      data={"grant_type": "refresh_token", "refresh_token": a0_refresh}, timeout=20)
    print("   status:", r.status_code, "body:", (r.text or "")[:300])

print("=" * 70)
print("4) Auth0 TOKEN với nhóm endpoint /auth0/account/*")
for path in ["ccarusermgnt/api/v1/auth0/account/profile",
             "ccarusermgnt/api/v1/auth0/account/client/credentials"]:
    h = app_headers()
    h["Authorization"] = f"Bearer {a0_tok}"
    h["Content-Type"] = "application/json"
    h["x-vin-code"] = "none"
    r = requests.get(f"{BASE}/{path}", headers=h, timeout=20)
    print(f"   [{r.status_code}] {path}")
    print("        body:", (r.text or "")[:400])
