# -*- coding: utf-8 -*-
# Ma trận test POST telemetry/ping: x-hash giả vs REPLAY x-hash thật từ HAR
# + GET khác để xác nhận GET nào cũng 200
import json, io, sys, base64, requests, uuid, time
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'

# Lấy x-hash + ts thật của 1 POST ping trong HAR
HAR = r'E:\ios\vinfast\logbypasssword.har'
d = json.load(open(HAR, encoding='utf-8'))
real_xh, real_ts, ping_body = 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
print('x-hash thật:', (real_xh or '')[:50], '| ts:', real_ts)
print('ping body app:', (ping_body or '')[:300])

def app_headers():
    dev = 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": "minhhai113he@gmail.com",
        "Authorization": f"Bearer {TOK}",
        "Content-Type": "application/json",
        "x-vin-code": VIN,
    }

body_reqs = json.loads(ping_body) if ping_body else [{"objectId":"34180","instanceId":"1","resourceId":"7"}]
print('số resource trong ping body:', len(body_reqs))

def run(label, method, url, extra=None, payload=None):
    h = app_headers()
    if extra: h.update(extra)
    if method == 'GET':
        r = requests.get(url, headers=h, timeout=20)
    else:
        r = requests.post(url, headers=h, json=payload, timeout=20)
    print(f"[{r.status_code}] {label}: {(r.text or '')[:150]}")
    return r

print()
run('GET  user-vehicle (baseline)', 'GET', f'{BASE}/ccarusermgnt/api/v1/user-vehicle')
run('GET  is-unread (GET khác)', 'GET', f'{BASE}/notimgmt/api/v1/notimgmt/users/app/is-unread')
print()
ts_now = str(int(time.time() * 1000))
run('POST ping KHÔNG x-hash', 'POST', f'{BASE}/ccaraccessmgmt/api/v1/telemetry/app/ping',
    payload=body_reqs)
run('POST ping x-hash GIẢ', 'POST', f'{BASE}/ccaraccessmgmt/api/v1/telemetry/app/ping',
    extra={'X-HASH': base64.b64encode(b'fake').decode(), 'X-TIMESTAMP': ts_now}, payload=body_reqs)
run('POST ping x-hash THẬT + ts GỐC (REPLAY)', 'POST', f'{BASE}/ccaraccessmgmt/api/v1/telemetry/app/ping',
    extra={'X-HASH': real_xh, 'X-TIMESTAMP': real_ts}, payload=body_reqs)
run('POST ping x-hash THẬT + ts HIỆN TẠI', 'POST', f'{BASE}/ccaraccessmgmt/api/v1/telemetry/app/ping',
    extra={'X-HASH': real_xh, 'X-TIMESTAMP': ts_now}, payload=body_reqs)
