# -*- coding: utf-8 -*-
# Dò DTO command v2: gửi messageContent -> server trả lỗi kế tiếp để lộ fields bắt buộc
import json, io, sys, requests, base64
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'
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": "minhhai113he@gmail.com",
        "Authorization": f"Bearer {TOK}",
        "Content-Type": "application/json",
        "x-vin-code": VIN,
    }

URL_V2 = BASE + '/ccaraccessmgmt/api/v2/remote/app/command'
URL_V3 = BASE + '/ccaraccessmgmt/api/v3/remote/app/command'

def show(label, url, payload):
    try:
        r = requests.post(url, headers=headers(), json=payload, timeout=20)
        print(f'[{r.status_code}] {label}: {(r.text or "")[:220]}')
    except Exception as e:
        print('[EXC]', label, e)

# === THỬ 1: commandType + messageContent rỗng {} (base64) — trả lỗi cho thấy field kế
body = {'commandType': 1, 'vinCode': VIN, 'params': {}, 'messageContent': base64.b64encode(b'{}').decode()}
show('V2 + messageContent(b64 empty)', URL_V2, body)

# === THỬ 2: messageContent là JSON string lệnh khóa cửa kiểu BMS
msg = json.dumps({'commandType': 1, 'vinCode': VIN, 'params': {}})
show('V2 + messageContent(json-string)', URL_V2,
     {'commandType': 1, 'vinCode': VIN, 'params': {}, 'messageContent': msg})

# === THỬ 3: V3 (endpoint mới trong dex) — body v2 cổ điển
show('V3 (body cũ)', URL_V3, {'commandType': 1, 'vinCode': VIN, 'params': {}})

# === THỬ 4: V3 với dạng signed (base64Data + signature) placeholder
show('V3 + data/signature giả', URL_V3,
     {'vinCode': VIN, 'data': base64.b64encode(b'{}').decode(), 'signature': base64.b64encode(b'x').decode()})
