# -*- coding: utf-8 -*-
# POST ping với DEVICE ID THẬT (đã trust) + so headers đủ chuẩn HAR
import json, io, sys, base64, requests
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

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'
INSTANCE = '02eae412-db18-4d42-8fd1-2928b57aecf6'

HAR = r'E:\ios\vinfast\logbypasssword.har'
d = json.load(open(HAR, encoding='utf-8'))
real_xh, real_ts, ping_body, ping_path = None, None, None, None
for e in d['log']['entries']:
    u = e['request']['url']
    if 'telemetry/app/ping' in u:
        for x in e['request']['headers']:
            if x['name'].lower() == 'x-hash': real_xh = x['value']
            if x['name'].lower() == 'x-timestamp': real_ts = x['value']
        pd = e['request'].get('postData', {})
        ping_body = pd.get('text')
        if ping_body and real_xh: break

body_reqs = json.loads(ping_body)
body_small = body_reqs[:10]
print('x-hash:', real_xh[:40], '| ts:', real_ts, '| n_res:', len(body_reqs))

def headers_for(dev, ua):
    return {
        "user-agent": ua,
        "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,
        "accept": "application/json",
        "accept-language": "vi-VN;q=1.0",
    }

def run(label, dev=DEV, ua=None, payload=None, extra=None):
    h = headers_for(dev, ua or f"iOS - {dev} - 2.26.11")
    if extra: h.update(extra)
    r = requests.post(f'{BASE}/ccaraccessmgmt/api/v1/telemetry/app/ping', headers=h, json=payload, timeout=20)
    print(f"[{r.status_code}] {label}: {(r.text or '')[:160]}")
    return r

print()
print('== TEST A: device THẬT + body nhỏ ==')
run('A1 dev-thật body10', payload=body_small)
print('== TEST B: device THẬT + body ĐỦ 100 (như app) + x-hash replay ==')
run('B1 dev-thật body100 + xhash replay', payload=body_reqs, extra={'X-HASH': real_xh, 'X-TIMESTAMP': real_ts})
print('== TEST C: device NGẪU NHIÊN + body100 + xhash replay ==')
import uuid
run('C1 dev-ngẫu-nhiên + xhash replay', dev=str(uuid.uuid4()).upper(), payload=body_reqs,
    extra={'X-HASH': real_xh, 'X-TIMESTAMP': real_ts})
