# -*- coding: utf-8 -*-
# 3 cửa: (1) grant_type=app với clientInstanceId THẬT từ HAR,
#         (2) Auth0 RS256 token (audience) trên /auth0/account/*,
#         (3) /auth0/account/* + x-hash HMAC Vinfast@2025
import requests, base64, io, sys, json, uuid, time, hashlib, hmac
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"
SECRET_HMAC = "Vinfast@2025"
REAL_INSTANCE = "02eae412-db18-4d42-8fd1-2928b57aecf6"
CRED = base64.b64encode(f"{CLIENT_ID}:{SECRET_NEW}".encode()).decode()

def x_hash_hmac(method, path, ts, vin=""):
    p = path.split("?")[0]
    if not p.startswith("/"): p = "/" + p
    msg = "_".join([method, p, vin, SECRET_HMAC, str(ts)] if vin else [method, p, SECRET_HMAC, str(ts)]).lower()
    return base64.b64encode(hmac.new(SECRET_HMAC.encode(), msg.encode(), hashlib.sha256).digest()).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 + clientInstanceId THẬT (chưa có signature)")
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": REAL_INSTANCE,
                        "timestamp": str(int(time.time() * 1000))}, timeout=20)
print("   status:", r.status_code, "body:", (r.text or "")[:300])

print("=" * 70)
print("2) Auth0 RS256 token (có audience) -> /auth0/account/*")
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)
a0 = r.json() if r.status_code == 200 else {}
tok = a0.get("access_token", "")
hdr_b64 = tok.split(".")[0]
hdr_b64 += "=" * (-len(hdr_b64) % 4)
print("   token header:", base64.urlsafe_b64decode(hdr_b64).decode()[:120], f"({len(tok)}ch)")

for path in ["ccarusermgnt/api/v1/auth0/account/profile",
             "ccarusermgnt/api/v1/auth0/account/client/credentials"]:
    for label, extra in [("plain", {}), ("x-hash HMAC", "X")]:
        h = app_headers()
        h["Authorization"] = f"Bearer {tok}"
        h["Content-Type"] = "application/json"
        h["x-vin-code"] = "none"
        if extra:
            ts = int(time.time() * 1000)
            h["X-HASH"] = x_hash_hmac("GET", path, ts)
            h["X-TIMESTAMP"] = str(ts)
        r = requests.get(f"{BASE}/{path}", headers=h, timeout=20)
        print(f"   [{r.status_code}] {path} ({label}): {(r.text or '')[:260]}")

print("=" * 70)
print("3) /ccarusermgnt/api/v1/user-vehicle với Auth0 RS256 + x-hash HMAC")
h = app_headers()
h["Authorization"] = f"Bearer {tok}"
h["Content-Type"] = "application/json"
h["x-vin-code"] = "none"
ts = int(time.time() * 1000)
h["X-HASH"] = x_hash_hmac("GET", "ccarusermgnt/api/v1/user-vehicle", ts)
h["X-TIMESTAMP"] = str(ts)
r = requests.get(f"{BASE}/ccarusermgnt/api/v1/user-vehicle", headers=h, timeout=20)
print("   status:", r.status_code, "body:", (r.text or "")[:400])
