# -*- coding: utf-8 -*-
# Gửi command v2 ĐỦ DTO (snake_case từ RemoteDataRequest) với signature GIẢ
# -> xem server từ chối ở tầng NÀO: signature/sess hay GÓI (để chốt gate gói nằm ở đâu)
import json, io, sys, requests, base64, time
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.path.insert(0, r'E:\ios\vinfast\vinfast-console')

INTERNAL = json.load(open(r'E:\ios\vinfast\vinfast-console\data\internal_token.json', encoding='utf-8'))
TOK = INTERNAL['access_token']
VIN = 'RLNV5JSE4TH730406'
EMAIL = 'minhhai113he@gmail.com'
BASE = 'https://mobile.connected-car.vinfast.vn'
DEV = '5ED66E61-C9B8-408D-B5CE-44275F59BB5F'

def headers():
    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,
        "Authorization": f"Bearer {TOK}",
        "Content-Type": "application/json",
        "x-vin-code": VIN,
    }

def post(label, url, body):
    r = requests.post(url, headers=headers(), json=body, timeout=20)
    print(f'[{r.status_code}] {label}: {(r.text or "")[:260]}')
    return r

URL_V2 = BASE + '/ccaraccessmgmt/api/v2/remote/app/command'
URL_V3 = BASE + '/ccaraccessmgmt/api/v3/remote/app/command'
sig = base64.b64encode(b'\x00' * 64).decode()
ts = str(int(time.time() * 1000))

# DTO v2 đầy đủ (snake_case — từ RemoteDataRequest d2 metadata):
# message_name, message_content, sess_id, timestamp, signature, tag, user_id,
# isMasterProfile, signature2, wakeUpTimeOut
body_v2 = {
    "message_name": "LOCK",
    "message_content": base64.b64encode(b'{}').decode(),
    "sess_id": "00000000-0000-0000-0000-000000000000",
    "timestamp": ts,
    "signature": sig,
    "tag": "tag",
    "user_id": EMAIL,
    "isMasterProfile": True,
    "signature2": sig,
    "wakeUpTimeOut": 60000,
}
post('V2 đủ-DTO snake_case (sig giả, sess giả)', URL_V2, body_v2)

# V2 nhưng KHÔNG signature (để xem thứ tự validation)
b2 = dict(body_v2); del b2['signature']; del b2['signature2']
post('V2 đủ-DTO KHÔNG signature', URL_V2, b2)

# V3 (mqttkit) — cần xem DTO nhưng thử trước dạng snake_case tương tự
post('V3 đủ-DTO snake_case', URL_V3, body_v2)

# verify-session với sess_id giả + phoneNumber/email THẬT (để xem server trả gì)
body_vs = {"sessionId": "00000000-0000-0000-0000-000000000000",
           "mobilePhone": "+84773448750", "email": EMAIL, "retry": False}
post('verify-session sess GIẢ + info THẬT', BASE + '/ccaraccessmgmt/api/v1/pairing/app/verify-session', body_vs)
