# -*- coding: utf-8 -*-
# Test password grant trên backend OAuth2 server của VinFast (/ccaruaa/oauth/token)
# Phát hiện từ HAR iOS: client Basic = capp8OXWD9bFbGiFG, secret mới = bqFgjKCB6SJjgL7m
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"
CLIENT_ID = "capp8OXWD9bFbGiFG"
SECRET_OLD = "Vinfast@2025"
SECRET_NEW = "bqFgjKCB6SJjgL7m"

def basic(cid, sec):
    return base64.b64encode(f"{cid}:{sec}".encode()).decode()

def app_headers(auth_basic):
    dev = str(uuid.uuid4()).upper()
    return {
        "Authorization": f"Basic {auth_basic}",
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "application/json",
        "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,
    }

def try_grant(name, secret, extra_fields):
    h = app_headers(basic(CLIENT_ID, secret))
    body = {"grant_type": "password", "username": EMAIL, "password": PASSWORD}
    body.update(extra_fields)
    try:
        r = requests.post(f"{BASE}/ccaruaa/oauth/token", headers=h, data=body, timeout=20)
        txt = (r.text or "")[:300]
        print(f"[{name}] status={r.status_code} body={txt}")
        if r.status_code == 200:
            return r.json()
    except Exception as e:
        print(f"[{name}] EXC: {e}")
    return None

results = {}
for name, secret, extra in [
    ("A: password + secret OLD (Vinfast@2025)", SECRET_OLD, {}),
    ("B: password + secret NEW (bqFgj...)", SECRET_NEW, {}),
    ("C: password + secret NEW + clientInstanceId+timestamp", SECRET_NEW,
     {"clientInstanceId": str(uuid.uuid4()), "timestamp": str(int(time.time() * 1000))}),
    ("D: password + secret OLD + clientInstanceId+timestamp", SECRET_OLD,
     {"clientInstanceId": str(uuid.uuid4()), "timestamp": str(int(time.time() * 1000))}),
]:
    j = try_grant(name, secret, extra)
    if j:
        results[name] = j
        break

tok = None
for name, j in results.items():
    tok = j.get("access_token")
    print("\n✅ THÀNH CÔNG:", name)
    for k, v in j.items():
        print(f"   {k}: {str(v)[:60]}")

# Nếu có token -> gọi ngay user-vehicle
if tok:
    print("\n== GỌI /ccarusermgnt/api/v1/user-vehicle với INTERNAL TOKEN ==")
    h = app_headers(basic(CLIENT_ID, secret))
    h["Authorization"] = f"Bearer {tok}"
    h["Content-Type"] = "application/json"
    h["x-vin-code"] = "none"
    r = requests.get(f"{BASE}/ccarusermgnt/api/v1/user-vehicle", headers=h, timeout=20)
    print("status:", r.status_code)
    print("body:", (r.text or "")[:800])
